views:

46

answers:

5

How would I go about selecting the data of each title from the following JSON? I have the JSON decoded, but I'm not sure how to select the part I want.

{
    "responseData": {
        "results": [
            {
                "title": "Justin Giesbrecht 749",
                "titleNoFormatting": "Justin Giesbrecht 749",
            },
            {
                "title": "Gopher dunes 09",
                "titleNoFormatting": "Gopher dunes 09",
            },
            {
                "title": "dirtbike Justin",
                "titleNoFormatting": "dirtbike Justin",
            },
            {
                "title": "A Warming",
                "titleNoFormatting": "A Warming",
            }
        ],
        "cursor": {
            "pages": [
                {
                    "start": "0",
                    "label": 1
                },
                {
                    "start": "4",
                    "label": 2
                }
            ],
            "estimatedResultCount": "6",
            "currentPageIndex": 0,
        }
    },
    "responseDetails": null,
    "responseStatus": 200
}

I thought it would be something like this, but I don't get anything:

echo "Response ". $jsonS->responseData->results[1]->title;
A: 

When you json_decode something it is converted to a regular PHP array, so you can reference it like $decodedObject["nodeName"].

Karl
Only if you pass true as the second ($assoc) parameter, it is..
Josh
As @Josh mentioned, this only works if you use `json_decode($json_data, true)`
mattbasta
A: 

Try:

echo "Response " . $jsonS['responseData']['results'][1]['title'];
dsclementsen
I received an error... Fatal error: Cannot use string offset as an array
Justin
A: 
Josh
+3  A: 

Actually you've got the reading of the title part right, it's the JSON that is invalid.

Copying the JSON into a JSON validator/lint e.g. http://www.jsonlint.com/ will show that the you have additional , (commas) after the last object attribute in a few places (5 places to be exact, after each 'titleFormatting' attribute and after 'currentPageIndex').

If you fix those errors and parse it using json_decode e.g.:

$jsonS = json_decode($json_text);

Then your own code:

echo "Response " . $jsonS->responseData->results[1]->title;

Will output the second (index 1 being the second index) results title

Response Gopher dunes 09

dsclementsen
+1: I answered that it was invalid, but your answer actually tells him *why*. Nice work!
Josh
Thank you, it was minor, but you were right! appreciate your time! Cheers. [answered]
Justin
A: 

In JSON you are not allowed to leave trailing comma in array/object definition. So, when in PHP is perfectly valid to write:

$a = array(1,2,3,);

(note last comma), in JSON

a : [1,2,3,] 

or

a : {x :'y',}

is invalid.

ts