Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add square braces around subarray data inside of a json encoded string?

Tags:

json

php

When trying to access an API the JSON array must be parsed like this

{"item":[{"id":"123456", "name":"adam"}]} 

But when i'm doing the following code

$data = array("item" => array("id" => "123456", "name" => "adam")); echo json_encode($data); 

it returns the json array without squared brackets as follows

{"item":{"id":"123456","name":"adam"}} 

I've spent hours trying to figure out how to fix this and just can't think of a solution

like image 926
Curtis Crewe Avatar asked Mar 21 '13 22:03

Curtis Crewe


People also ask

How do you use square brackets in JSON?

Curly braces hold objects and each name is followed by ':'(colon), the name/value pairs are separated by , (comma). Square brackets hold arrays and values are separated by ,(comma).

Are square brackets allowed in JSON?

JSON (JavaScript Object Notation) This makes JSON human-readable. JSON is easier to parse than XML. This is because JSON uses a fixed set of delimiters. These delimiters include curly braces ({ }), commas (,), colons (:) and square brackets ([]).

What is a [] in JSON?

' { } ' used for Object and ' [] ' is used for Array in json.

Does JSON need curly braces?

A JSON object contains zero, one, or more key-value pairs, also called properties. The object is surrounded by curly braces {} . Every key-value pair is separated by a comma. The order of the key-value pair is irrelevant.


2 Answers

You need to wrap things in another array:

$data = array("item" => array(array("id" => "123456", "name" => "adam"))); 

This will be more understandable if we use the equivalent PHP 5.4 array syntax:

$data = [ "item" => [ ["id" => "123456", "name" => "adam"] ] ]; 

Compare this with the JSON:

        { "item":   [ {"id":"123456", "name":"adam"      } ] } 

The only thing to explain is why one of the PHP arrays remains an array [] in JSON while the other two get converted to an object {}. But the documentation already does so:

When encoding an array, if the keys are not a continuous numeric sequence starting from 0, all keys are encoded as strings, and specified explicitly for each key-value pair.

like image 52
Jon Avatar answered Oct 07 '22 17:10

Jon


Before reading this post, I had this:

echo json_encode($data);

After reading this post:

echo json_encode(array($data)); 

Brackets appeared at the start and end of the JSON object.

like image 26
Chad Avatar answered Oct 07 '22 16:10

Chad