Swiftyjson: Why can't we parse a rawString back to json object?

Created on 25 Nov 2014  路  13Comments  路  Source: SwiftyJSON/SwiftyJSON

var obj = JSON("...")
var str = obj.rawString()
var anotherObj = JSON(str)

this does not work. Why?

Most helpful comment

I had the same issue. I got it working by using JSON.parse(myString) instead

All 13 comments

try

var anotherObj = JSON(str!)

There is a problem after parsing rawString back to json object though:

let json = JSON(["user":"name"])
println(json["user"]) --> name
let jsonStr = json.rawString()!
let json2 = JSON(jsonStr)
println(json2["user"]) --> null

What may I have done wrong? Thanks!!

Same issue here.

let json = JSON(["user":"name"])
println(json["user"])
let data = json.rawString()!.dataUsingEncoding(NSUTF8StringEncoding)!
let json2 = JSON(data: data)
println(json2["user"])

It works

Try

public func rawData(options opt: NSJSONWritingOptions = NSJSONWritingOptions(0), error: NSErrorPointer = nil) -> NSData?

I got the same issue with version 1.3.1
var obj = JSON("...")
var str = obj.rawString()
var anotherObj = JSON(str)
I cannot fetch any property of "anotherObj". Yes, rawData() can work here, but I really need store the string value, why it cannot unserialize the rawString

I had the same issue. I got it working by using JSON.parse(myString) instead

How to remove white spaces and newlines with rawString()?

I came across the same issue and wasted a lot of time here. The solution provided by @peterjuras finally solve my problem. This is definitely an awful bug.

I've had the same issue, have been doubting myself for days. Thank you @peterjuras, you're solution worked.

I feel the above solution should be part of the official document. @peterjuras Thanks for sharing.

JSON.parse is deprecated, use JSON.init(parseJSON: "your json string")

JSON.parse is deprecated, use JSON.init(parseJSON: "your json string")

Where did you find this info??

@leochoo A quick search through the SwiftyJSON.swift source file looking for init() methods.

https://github.com/SwiftyJSON/SwiftyJSON/blob/184c6884998c41f71a73c459f9b525b7121be846/Source/SwiftyJSON.swift#L125

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rbugajewski picture rbugajewski  路  17Comments

DarthRamone picture DarthRamone  路  17Comments

KyeMaloy97 picture KyeMaloy97  路  12Comments

debayanb picture debayanb  路  12Comments

Joe2Code picture Joe2Code  路  12Comments