Rami
Rami

Reputation: 171

How to parse json object containing json array in laravel

i've build an API for myself to return some data , this data is returned in json form like that

{
[
    {
        "name": "John Doe",
        "year": "1st",
        "curriculum": "Arts"
    }
]}

the problem is that i can't accesss any field of this data , i've been trying it on REST client by these inputs

{
"test" : {
[
    {
        "name": "John Doe",
        "year": "1st",
        "curriculum": "Arts"
    }
]}}

the "test" is the name of the input passed from the android to the API.

when i make a request like the above i get nothing , but when doing something like

{
"test" : 
[
    {
        "name": "John Doe",
        "year": "1st",
        "curriculum": "Arts"
    }
]}

handling it with this code

$test = $request->input('test');
    $final_Length_Array = array('list', $test);
    $var = $final_Length_Array[1][0]['name'];

    return response()->json([
        'state' => '1',

        'test' => $var
    ]);

i get me desired value , now if any one can tell me how to deal with it ?

Upvotes: 0

Views: 822

Answers (1)

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40909

This is not a valid JSON value:

{
  "test" : {
    [
      {
        "name": "John Doe",
        "year": "1st",
        "curriculum": "Arts"
      }
    ]
  }
}

The value of the test key is an object and it should contain key-value pairs, not a list.

In the future you can use the online validator to check, if given string is a JSON value, e.g. https://jsonlint.com/. Please also have a look at the JSON specification a thttp://www.json.org/ to see what it should look like.

Upvotes: 2

Related Questions