I’m just playing with the JSON parser in iOS it’s working fine as a ( simple ) example . But I was wonder how one would actually parse something (a bit) more complicated, the a Twitter trends JSON, like this :
{
"trends": {
"2011-03-13 11:42:17": [
{
"events": null,
"query": "Fukushima",
"promoted_content": null,
"name": "Fukushima"
},
{
"events": null,
"query": "Rebecca Black",
"promoted_content": null,
"name": "Rebecca Black"
},
{
"events": null,
"query": "Pearl Harbour",
"promoted_content": null,
"name": "Pearl Harbour"
},
...
{
"events": null,
"query": "Magdalena Neuner",
"promoted_content": null,
"name": "Magdalena Neuner"
}
]
},
"as_of": 1300016537
}
How would one just return the first 3 queries ? in this instance : Fukushima, Rebecca Black and Pearl Harbour .
Using the example code, it goes something like this :
for (int i = 0; i < [luckyNumbers count]; i++)
[text appendFormat:@"%@\n", [luckyNumbers objectAtIndex:i]];
This is for a much simpler feed though, can it be approached the same way for what I’m looking for ?
EDIT
I am now trying to return the value of “query”:
So I`m doing this :
NSLog(@"%@", [[luckyNumbers objectForKey:@"trends"]);
This of course logs the content of the key “trend”, how do I go about returning not only the first ( and only ) key of trends but also dig one more level down to return the content of “query” ??
I’ve also tried something like this :
NSString *date = [[[luckyNumbers valueForKeyPath:@"trends"] allKeys] description];
NSArray *trends = [luckyNumbers objectForKey:@"trends"];
NSLog(@"%@", [trends valueForKeyPath:date]);
but no go …
JSON maps like for like to dictionaries and arrays – that’s the point of it (versus XML). How you would get information out of a particular JSON file would depend on how that file was designed in the first place.
Square brackets in JSON indicate arrays – curly braces indicate dictionaries (objects). So in your example we see that there’s a dictionary containing an object with the key ‘trends’, an object that itself is a dictionary.
It’s going to be easier for you to get a handle on this if you log the output of your parsed array, because you’ll see the entire structure of NSArrays and NSDictionaries. To do this, once you’ve parsed your JSON you’d want to do something like:
NSLog([parsedJsonResult description]);