Home > Back-end >  How can I get this code to print the right JSON schema?
How can I get this code to print the right JSON schema?

Time:08-25

I'm trying to make a php script which will output json like this:

{"lots":[{"Id":32932,"Type":"G","x":1,"y":2,"z":3},{"Id":32933,"Type":"R","x":4,"y":5,"z":6}]

My php script looks like this, and this is the output:

$lots = array("lots");

$lots[] = array("Id" => 32932, "Type" => "G", "x" => 1, "y" => 2, "z" => 3);
$lots[] = array("Id" => 32933, "Type" => "R", "x" => 4, "y" => 5, "z" => 6);

$json = json_encode($lots);

echo $json;

output:

["lots",{"Id":32932,"Type":"G","x":1,"y":2,"z":3},{"Id":32933,"Type":"R","x":4,"y":5,"z":6}]

As you can see it comes out kind of different structure.

If I use the php generated json, this is the error:

ArgumentException: JSON must represent an object type.

I have another C# Unity project which is expecting the JSON to be in the first format. How do I get my PHP code to output in the right schema?

CodePudding user response:

To get the output you want, the PHP should be:

$lots = array();

$lots["lots"][] = array("Id" => 32932, "Type" => "G", "x" => 1, "y" => 2, "z" => 3);
$lots["lots"][] = array("Id" => 32933, "Type" => "R", "x" => 4, "y" => 5, "z" => 6);

$json = json_encode($lots);

echo $json;

Live demo: https://3v4l.org/9UlGX

Your version was creating an array element with the value "lots" (and implicitly a numeric key of 0), rather than creating a key called "lots" and assigning items to it.

CodePudding user response:

The Json from your PHP script generates an array that has one string with "lots" and two objects in it, so naturally it can't be serialized.

You'd have to change it so that your PHP script generates a json starting with curly bracets that has an element calles "lots" in it with an array that has objects in it then the second one will also work.

  • Related