I am having a problem using json_encode to generate a json encoded string from an array.
The section of the array in question looks like this
RatingDistribution (Array, 11 elements)
0 (Array, 1 element)
0 (String, 3 characters ) 4.5
1 (Array, 1 element)
1 (String, 4 characters ) 11.9
2 (Array, 1 element)
But produces this in the string:
"RatingDistribution":[["4.5"],{"1":"11.9"},
I would expect this:
"RatingDistribution":[{"0":"4.5"},{"1":"11.9"},
All I'm doing is this:
$result = json_encode($array);
Have I done something wrong or do I need more code to ensure the 0 key is present?
Cheers Andy
The json_encode() function is used to encode a value to JSON format.
json_encode — Returns the JSON representation of a value.
PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true.
To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.
If you want to use arrays in your json then instead of JSON_FORCE_OBJECT
parameter you can simply cast array to object.
Problem:
json_encode([0 => [1,2,3]]); // Return: [[1,2,3]]
json_encode(["0" => [1,2,3]]); // Return: [[1,2,3]]
json_encode([1 => [1,2,3]]); // Return: {"1":[1,2,3]}
Not what we expect :
json_encode([0 => [1,2,3]], JSON_FORCE_OBJECT); // Return: {"0":{"0":1,"1":2,"2":3}}
Solution:
json_encode((object)[0 => [1,2,3]]); // Return: {"0":[1,2,3]}
json_encode(new \ArrayObject([0 => [1,2,3]])); // Return: {"0":[1,2,3]}
The result you are getting should be expected; json_encode
detects that you are only using numeric keys in the array, so it translates that to an array instead of an object in JSON. Most of the time, that's exactly what you want to do.
If for some reason you don't (why?), in PHP >= 5.3 you can use the JSON_FORCE_OBJECT
flag to get your desired output:
$result = json_encode($array, JSON_FORCE_OBJECT);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With