45

I am trying to parse data from a JSON file. I am trying to put that parsed/fetched data into a UIView with a label or in a webview. The JSON file looks something like the following:

{"bodytext": "<p>\n Some lines here about some webpage (&ldquo; <em>Site</>&rdquo;) some more lines here. \n </p>\n\n <p>\n some more stuff here </p> } 

There are posts here on Stack Overflow showing how to parse JSON retrieved from a Web URL, but I actually already have a JSON file I want to parse. How do I parse JSON from a file?

1
  • Just made the json file an html file and read it and displayed it on the web view. If anyone has a better way of doing this, please comment and let me know. Commented Aug 30, 2013 at 18:29

3 Answers 3

124
  1. Create empty text file (New File/Other/Empty) e.g. "example.json"

  2. Paste json string into the file.

  3. Use these lines to get the data:

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"example" ofType:@"json"]; NSData *data = [NSData dataWithContentsOfFile:filePath]; NSArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]; 
Sign up to request clarification or add additional context in comments.

3 Comments

I copy pasted this snippet more than 100 times in the last month
@lucaslt89 time to make it an Xcode snippet: nshipster.com/xcode-snippets
or maybe some helper class/category
18

Swift 2.0 version of the accepted answer:

if let filePath = NSBundle.mainBundle().pathForResource("example", ofType: "json"), data = NSData(contentsOfFile: filePath) { do { let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) } catch { //Handle error } } 

Comments

7

I have followed this and it is working fine

NSError *error = nil; NSString *filePath = [[NSBundle mainBundle] pathForResource:@"messages" ofType:@"json"]; NSData *dataFromFile = [NSData dataWithContentsOfFile:filePath]; NSDictionary *data = [NSJSONSerialization JSONObjectWithData:dataFromFile options:kNilOptions error:&error]; if (error != nil) { NSLog(@"Error: was not able to load messages."); return nil; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.