3

I am building an app that uses a UPC data base API. I am getting back a JSON object, example from here: http://www.simpleupc.com/api/methods/FetchNutritionFactsByUPC.php

{
"success":true,
"usedExternal":false,
"result"
    {
        "calories_per_serving":"150",
        "cholesterol_per_serving":"15",
        "cholesterol_uom":"Mg",
        "dvp_calcium":"30",
        "dvp_cholesterol":"4",
        "dvp_iron":"2",
        "dvp_protein":"17",
        "dvp_saturated_fat":"8",
        "dvp_sodium":"10",
        "dvp_total_fat":"4",
        "dvp_vitamin_a":"10","
        "dvp_vitamin_c":"0",
        "dvp_vitamin_d":"25",
        "fat_calories_per_serving":"25",
        "fiber_per_serving":"<1",
        "fiber_uom":"G",
        "ingredients":"Fat Free Milk, Milk, Sugar, Cocoa (Processed With Alkali),
                       Salt, Carrageenan, Vanillin (Artificial Flavor),
                       Lactase Enzyme, Vitamin A Palmitate And Vitamin D3.",
        "protein_per_serving":"8",
        "protein_uom":"G",
        "size":"240",
        "units":"mL",
        "servings_per_container":"8",
        "sodium_per_serving":"230",
        "sodium_uom":"Mg",
        "total_fat_per_serving":"2.5",
        "total_fat_uom":"G",
        "trans_fat_per_serving":"0",
        "trans_fat_uom":"G",
        "upc":"041383096013"
    }
}

My problem is with parsing the "ingredients" element, which is a sub list of the object dictionary.

How would you suggest parsing the ingredients list? If I could get it to an NSArray, assuming commas are separators, that would have been great.

I tried to do this, but looks like its just a string, so no way to parse it.

Any suggestion would be more than welcome. Thanks!

   //Thats the whole JSON object
    NSDictionary *json_dict = [theResponseString JSONValue];


   //Getting "results" which has all the product info
    NSArray *myArray = [[NSArray alloc] init];
     myArray = [json_dict valueForKey:@"result"];

Now how do I get "ingredients" from myArray in an array form?

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
TommyG
  • 4,145
  • 10
  • 42
  • 66

2 Answers2

7

You're getting result as an array, but (in JSON terminology) it's not an array. It's an object, so use an NSDictionary. Something like this:1

NSDictionary *result = [json_dict objectForKey:@"result"];

Then you can get the inner ingredients object from that:

NSString *ingredients = [result objectForKey:@"ingredients"];

Edited as per @Bavarious' comment.


1Apologies for glaring errors, as I'm not terribly well-versed in Objective-C. You might need to allocate memory for the returned NSDictionary and NSString pointers; I'm not sure.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • thanks, but i need ingredients in an array form so I could access each one of of the ingredients. – TommyG Nov 01 '11 at 23:51
  • That's all well and good. Unfortunately for your purposes, you're stuck with the format in the JSON. That means you first must retrieve the ingredients as a string, and then split that string on `,` (comma) into an array. I agree that the JSON format is stupid, but must play the hand you're dealt. Or, y'know, use a different API. – Matt Ball Nov 01 '11 at 23:54
  • RTFM, man. [`-[NSString componentsSeparatedByString]`](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/componentsSeparatedByString:) or [search SO](http://stackoverflow.com/search?q=%5Bobjective-c%5D+string+split) – Matt Ball Nov 01 '11 at 23:56
  • 1
    I suggest using `-objectForKey:`, the canonical `NSDictionary` method to retrieve elements from a dictionary, instead of `-valueForKey:`. See http://stackoverflow.com/questions/4489684/difference-valueforkey-objectforkey –  Nov 02 '11 at 00:14
  • @Bavarious thank you, edited accordingly. Like I said: I don't really know Objective-C. – Matt Ball Nov 02 '11 at 00:26
3

Here's all you need to do:

 NSDictionary *json_dict = [theResponseString JSONValue];

 // Use a key path to access the nested element.
 NSArray *myArray = [json_dict valueForKeyPath:@"result.ingredients"];

EDIT

Whoops, Matt's right. Here's how to deal with the string value:

 // Use a key path to access the nested element.
 NSString *s = [json_dict valueForKeyPath:@"result.ingredients"];
 NSArray *ingredients = [s componentsSeparatedByString:@", "];

Note that you might need to trim the '.' character off the last element of the array.

jlehr
  • 15,557
  • 5
  • 43
  • 45
  • Look at the JSON carefully. `result.ingredients` is not an array. It's a string. – Matt Ball Nov 01 '11 at 23:58
  • nice try - could have been nice and clean, but myArray is not array in that case - its a string (also, running "count" on it crashes the app). – TommyG Nov 02 '11 at 00:07
  • Matt is right - its a string, so has to go brute force so it seems. – TommyG Nov 02 '11 at 00:08