JSON format sometimes not same, how to extract the info from the different JSON format?

66 views Asked by At

I'm using this to get the auto suggestion from Youtube.

http://suggestqueries.google.com/complete/search?hl=en&ds=yt&client=youtube&hjson=t&cp=1&q=Like&format=5&alt=json

["Tire",[["tired",0],["tired lyrics",0],["tired alan walker remix",0],["tired remix",0],["tired alan walker cover",0],["tired of being sorry enrique iglesias",0],["tire",0],["tired cover",0],["tiren mati kemaren full movie",0],["tired of talking",0]],{"k":1,"q":"raN20uYZUrouYBB7VsB396HlA88"}]

As you can see from above to extract the information from above, I am using this code to extract the information such as tired, tired lyrics, tired alan walker from the JSON array.

NSString *json = nil;
    NSScanner *scanner = [NSScanner scannerWithString:str];
    [scanner scanUpToString:@"[[" intoString:NULL]; // Scan to where the JSON begins
    [scanner scanUpToString:@"]]" intoString:&json];

    NSLog(@"json before = %@", json);
            //The idea is to identify where the "real" JSON begins and ends.
    json = [NSString stringWithFormat:@"%@%@", json, @"]]"];

but sometimes the JSON array might be this format as shown below.

["Like",[["likey",0,[131]],["likey twice lyrics",0,[3]],["likey dance",0,[3]],["likey dance practice",0,[3]],["likey live",0,[3]],["like i\u0027m gonna lose you",0],["like ooh ahh",0],["like a boss",0],["like a g6",0],["like a stone",0]],{"k":1,"q":"9DuLDtNkAUfZ2X9AVZN90t0Zxlw"}]

How can i extract the information above example like likey, likey twice lyrics ?

1

There are 1 answers

0
Warren Burton On BEST ANSWER

NSScanner isn't the best API for turning raw JSON into useful data.

You would be best served by using the native JSON API NSJSONSerialization

id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

The json object can be cast into NSArray in your case here.

where the data is the raw data from the response.

see also this answer