why do javascript libraries using json choose a [ { } , { } ] structure
javascript, json, php
Solution
Because that's the logical way how to pass multiple objects. It's probably made to facilitate this:
[{"foo" : "bar", "12" : "true"}, {"foo" : "baz", "12" : "false"}]
Use the same logical structure in PHP:
echo json_encode(array(array("foo" => "bar", "12" => "true")));
Problem
I've been using a few javascript libraries, and I noticed that most of them take input in this form: `[{"foo": "bar", "12": "true"}]` According to json.org: So we are sending an object in an array. So I have a two part question: Part 1: Why not just send an object or an array, which would seem simpler? Part2: What is the best way to create such a Json with Php? Here is a working method, but I found it a bit ugly as it does not work out of the box with multi-dimensional arrays: ``` <?php $object[0] = array("foo" => "bar", 12 => true); $encoded_object = json_encode($object); ?> ``` output: `{"1": {"foo": "bar", "12": "true"}}` ``` <?php $encoded = json_encode(array_values($object)); ?> ``` output: `[{"foo": "bar", "12": "true"}]`