Try as I might, I couldn't figure out an elegant way to get window.fruitsAndVeggies
into a dictionary. The best I could do was to hand-roll a loop that iterates through the javascript object and adds each key/value pair to a dictionary one-by-one.
The code's below. Be warned: it's ugly. If you've got a more succinct solution, I'm all ears!
/* Make the dictionary. */
NSMutableDictionary *fruitsAndVeggiesDict = [NSMutableDictionary dictionary];
/* In the JS context, create a variable called "keys".
Return the number of keys (keys.length). */
result = JSEvaluateScript( ctx, JSStringCreateWithUTF8CString("var keys = Object.keys(window.fruitsAndVeggies.name2CategoryMap); keys.length"), NULL, NULL, 0, &exception );
double numKeys = JSValueToNumber(ctx, result, &exception);
/* Iterate over the keys; convert each key/value into a pair of NSStrings. */
for(int i = 0; i < numKeys; i++){
// get a key, save in keyStrNS
NSString *getKeyStr = [NSString stringWithFormat:@"keys[%d]", i];
CFStringRef getKeyStrCF = (__bridge CFStringRef)getKeyStr;
JSStringRef getKeyStrJS = JSStringCreateWithCFString(getKeyStrCF);
JSValueRef key = JSEvaluateScript( ctx, getKeyStrJS, NULL, NULL, 0, &exception );
JSStringRef keyStrJS = JSValueToStringCopy(ctx, key, &exception);
NSString *keyStrNS = (NSString *)JSStringCopyCFString( kCFAllocatorDefault, keyStrJS );
// get a value, save in valueStrNS
NSString *getValueStr = [NSString stringWithFormat:@"window.fruitsAndVeggies.name2CategoryMap[\"%@\"]", keyStrNS];
CFStringRef getValueStrCF = (__bridge CFStringRef)getValueStr;
JSStringRef getValueStrJS = JSStringCreateWithCFString(getValueStrCF);
JSValueRef value = JSEvaluateScript( ctx, getValueStrJS, NULL, NULL, 0, &exception );
JSStringRef valueStrJS = JSValueToStringCopy(ctx, value, &exception);
NSString *valueStrNS = (NSString *)JSStringCopyCFString( kCFAllocatorDefault, valueStrJS );
/* store the key and value in our dictionary */
[fruitsAndVeggiesDict setObject: valueStrNS forKey: keyStrNS];
/* and print them for good measure */
NSLog(@"key %@ has value %@",keyStrNS,valueStrNS);
}
Output:
key apple has value fruit
key carrot has value vegetable