Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why do javascript libraries using json choose a [ { } , { } ] structure

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:

enter image description here

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"}]

like image 440
L. Sanna Avatar asked Jan 15 '23 17:01

L. Sanna


1 Answers

  1. 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"}]
    
  2. Use the same logical structure in PHP:

    echo json_encode(array(array("foo" => "bar", "12" => "true")));
    
like image 76
deceze Avatar answered Jan 18 '23 08:01

deceze