user896692
user896692

Reputation: 2371

Parsing JSON in PHP

I´ve got the following JSON string:

{"Data":{"Recipes":{"Recipe_5":{"ID":"5","TITLE":"Spaghetti Bolognese"},"Recipe_7":{"ID":"7","TITLE":"Wurstel"},"Recipe_9":{"ID":"9","TITLE":"Schnitzel"},"Recipe_10":{"ID":"10","TITLE":null},"Recipe_19":{"ID":"19","TITLE":null},"Recipe_20":{"ID":"20","TITLE":"Hundefutter"},"Recipe_26":{"ID":"26","TITLE":"Apfelstrudel"},"Recipe_37":{"ID":"37","TITLE":null},"Recipe_38":{"ID":"38","TITLE":"AENDERUNG"},"Recipe_39":{"ID":"39","TITLE":null},"Recipe_40":{"ID":"40","TITLE":"Schnitzel"},"Recipe_42":{"ID":"42","TITLE":"Release-Test"},"Recipe_43":{"ID":"43","TITLE":"Wurstel2"}},"recipes_id":{"ranking_1":"9","ranking_2":"10","ranking_3":"7","ranking_4":"5"}},"Message":null,"Code":200}

How can I parse it in PHP and extract a list of TITLEs?

Upvotes: 0

Views: 257

Answers (2)

Jan Pöschko
Jan Pöschko

Reputation: 5580

You can use the function json_decode to parse JSON data in PHP (>= 5.2.0, at least). Once you have a PHP object, it should be easy to iterate over all recipes/members and access their titles, using something like this:

$data = json_decode($json, true); // yields associative arrays instead of objects
foreach ($data['Data']['Recipes'] as $key => $recipe) {
    echo $recipe['TITLE'];
}

(Sorry I can't actually run this code right now. Hope it helps anyway.)

Upvotes: 3

Jan Pöschko
Jan Pöschko

Reputation: 5580

If you want to do that in JavaScript, you can simply access JSON data like "normal" objects:

var jsonData = {
    "Data": {"Recipes": {"Recipe_5": {"ID":"5","TITLE":"Spaghetti Bolognese"}}}
    // more data
};
alert(jsonData.Data.Recipes.Recipe_5.TITLE);

This will print the TITLE of Recipe_5 in a message box.

EDIT:

If you want all the titles in a list, you can do something like this:

var titles = [];
for (var key in jsonData.Data.Recipes) {
    var recipe = jsonData.Data.Recipes[key];
    titles.push(recipe.TITLE);
}
alert(titles);

Upvotes: 0

Related Questions