Json object format

I am retrieving data to my database, and this is the result

[
  {
                firstname: 'Harley',
                lastname: 'Shane'
            },
            {
                firstname: 'Angel',
                lastname: 'Miller'
            },
            {
                firstname: 'Margaret',
                lastname: 'Finley'
            }
  ]

how can I remove the '[' and ']'

or how can I just return the data without this , like this only

{
            firstname: 'Harley',
            lastname: 'Shane'
        },
        {
            firstname: 'Angel',
            lastname: 'Miller'
        },
        {
            firstname: 'Margaret',
            lastname: 'Finley'
        }

here is my snippet

 $data = array();
       foreach($result as $row){
           $data [] = array('firstname'=>$row['firstname'],'lastname'=> $row['lastname']);
       }

       echo json_encode($data);

Thank you in advance

That indicates that it is an array and the element you want to return is in position [0] of that array.

Take a trip to jsonlint.com and try changing the format and see how you get on. This is actually correct JSON:

[
    {
        "firstname": "Harley",
        "lastname": "Shane"
    },
    {
        "firstname": "Angel",
        "lastname": "Miller"
    },
    {
        "firstname": "Margaret",
        "lastname": "Finley"
    }
]

[ to ] indicates that you have an array, as @felgall mentioned. So you have an array of objects, denoted by the { and } characters. Each object has a firstname and lastname field. This is synonymous with this in PHP:

$foo = [
    [
        'firstname' => 'Harley',
        'lastname' => 'Shane'
    ],
    [
        'firstname' => 'Angel',
        'lastname' => 'Miller'
    ],
    [
        'firstname' => 'Margaret',
        'lastname' => 'Finley'
    ]
];

Or, if you’re more old fashioned :wink:

$foo = array(
    array(
        'firstname' => 'Harley',
        'lastname' => 'Shane'
    ),
    array(
        'firstname' => 'Angel',
        'lastname' => 'Miller'
    ),
    array(
        'firstname' => 'Margaret',
        'lastname' => 'Finley'
    )
);

If you were to take the [ and ] characters away it would be like taking away that first array() in the PHP examples, so you’d have no container for the remaining data.

Bear in mind that JSON is a little different to PHP: An array in PHP can have named keys (ie firstname and lastname) whereas in JSON it cannot. If you want to use named keys then you create a simple object, which is the { and } characters. As a result, a json_encode() will convert that top-level PHP array into a JS array, but the nested arrays with their named keys will be converted into a JS object.

@felgall , @Antnee,

Thank you :smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.