Last Updated: February 25, 2016
·
3.309K
· anthonylevings

JSON and the JavaScriptCore Framework (Xcode/iOS)

In order to use the JavaScriptCore Framework in your iOS app you'll need to add the Framework to your app by navigating to Targets > General > Linked Frameworks and Libraries and adding it in.

Then use #import in the .h file of your view controller to include it: #import <JavaScriptCore/JavaScriptCore.h>

You will then be able to run this code

//
//  JSViewController.m
//  JavaScriptCore
//
//

#import "JSViewController.h"


@interface JSViewController ()

@end

@implementation JSViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
 // Do any additional setup after loading the view, typically from a nib.

    // Establish path to JSON file
    NSString* path = [[NSBundle mainBundle] pathForResource:@"book"
                                                     ofType:@"json"];
    // Load contents into a string
    NSString* content = [NSString stringWithContentsOfFile:path
                                                  encoding:NSUTF8StringEncoding
                                                     error:NULL];

    // First a context and JS virtual machine is created
    JSContext *context = [[JSContext alloc] initWithVirtualMachine:[[JSVirtualMachine alloc] init]];

    // Next we send the context a function
    [context evaluateScript:@"var valueForKeyTitle = function(json) {var obj = JSON.parse(json); return(obj.Title);}"];

    // Prepare a JSValue to receive the JSON
    JSValue *returnElement = context[@"valueForKeyTitle"];

    // Call the function by sending JSON
    JSValue *resultOfFunction = [returnElement callWithArguments:@[content]];

    // Print result in console
    NSLog(@"Book Title: %@", resultOfFunction);      
}

@end

assuming you have a local json file called book.json in your app with the following contents:

{"Title":"Greatest Book in the World!!", "Length":214}

For further details, see full blogpost.

See also this Big Nerd Ranch post.