0

I can't seem to work out how to get a Dictionary representing an object from the dictionary that TouchJSON returns.

For example:

If I use the JSON in the format here:

http://search.twitter.com/search.json?q=hello

How would I get a tweet with the "id" = x without having to pull all of the tweets into an array using a "for" statement?

e.g. without having to do this... since I know the "id" (JSON key, rather than index) of the object I want to access

NSArray *tweetsArray = [resultsDictionary objectForKey:@"results"];
 for (NSDictionary *tweetDictionary in tweetsArray) {
     NSString *tweetText = [tweetDictionary objectForKey:@"text"];
     [tweets addObject:tweetText];

 }
mac_55
  • 4,130
  • 7
  • 31
  • 40
  • What's wrong with your sample code? You could try to parse the JSON string yourself, but I'm not sure what you're trying to achieve. – Christopher Pickslay Jul 07 '10 at 05:27
  • Well, I don't really want to waste resources parsing the whole string into an array when I know exactly which child of the 'results' node that I'm looking for. I assumed there'd be a simpler way? – mac_55 Jul 07 '10 at 11:38

2 Answers2

1

You can use NSPredicate to filter the tweetsArray like this:

NSArray *tweetsArray = [resultsDictionary objectForKey:@"results"];
NSArray* filtered = [test filteredArrayUsingPredicate:
                          [NSPredicate predicateWithFormat:@"id = %@",@"456"]];

NSDictionary* tweet = [filtered lastObject];
tonklon
  • 6,777
  • 2
  • 30
  • 36
  • Did this answer your question?, then please mark as answered. Or have I misunderstood it? – tonklon Jul 16 '10 at 20:10
  • 1
    I don't know what exactly the filteredArrayUsingPredicate: do, but I think it still has to loop over the array some ways and it looks like a performance problem to the questioner. Take a look at the question again: " How would I get a tweet with the "id" = x without having to pull all of the tweets into an array using a "for" statement? " – vodkhang Jul 17 '10 at 13:50
0

Why don't you filter the id=x condition when you are parsing the JSON. This will make sure you traverse the JSON data only once.

This can only be a better solution if you have to access the JSON just for the id=x condition.

Girish Kolari
  • 2,515
  • 2
  • 24
  • 34