Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JSON from String not working #2

Closed
itssimon opened this issue Sep 8, 2015 · 4 comments
Closed

JSON from String not working #2

itssimon opened this issue Sep 8, 2015 · 4 comments

Comments

@itssimon
Copy link

itssimon commented Sep 8, 2015

In the playground try this (branch swift-2.0):

import JASON

let json = JSON("{\"name\": \"foo\"}")
json["name"].stringValue

I'd expect the last line to show "foo". But it doesn't.

@BluMist
Copy link

BluMist commented Sep 13, 2015

You want to actually invoke the init(NSData?) to get the JSON functionality. Otherwise, json.object in your example is just a literal string.

To convert string into NSData:

import JASON

let jsonString: NSString = "{"name": "foo"}"
let data = jsonString.dataUsingEncoding(NSUTF8StringEncoding)

let json = JSON(data)
json["name"].stringValue

@itssimon
Copy link
Author

Ah, I see. Wouldn't it be nice if there was a JSON.init(String) or a static method JSON.fromString(String) that did just that? Otherwise it would be good to mention this in the README

@BluMist
Copy link

BluMist commented Sep 14, 2015

Most of the time, you'll either be reading the JSON from a file or from an API response. Both of those are usually read as NSData, which can then be plugged into the init()

It'd be quite cumbersome to construct JSON strings manually ;)

@delba
Copy link
Owner

delba commented Nov 2, 2015

Hey @itssimon, initializing JASON from a raw string of JSON doesn't work and there is no plan to support this in the future.

Meanwhile, if you want to read JSON from a file, you can write something like this:

if let path = NSBundle.mainBundle().pathForResource("person", ofType: "json"),
    data = try? NSData(contentsOfFile: path) {
        let json = JSON(data)
        print(json["name"].stringValue)
}

Thanks for the support @BluMist 😉

@delba delba closed this as completed Nov 2, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants