Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string into JSON using SwiftyJSON

The string to convert:

[{"description": "Hi","id":2,"img":"hi.png"},{"description": "pet","id":10,"img":"pet.png"},{"description": "Hello! :D","id":12,"img":"hello.png"}]

The code to convert the string:

var json = JSON(stringLiteral: stringJSON)

The string is converted to JSON and when I try to count how many blocks are inside this JSON (expected answer = 3), I get 0.

print(json.count)

Console Output: 0

What am I missing? Help is very appreciated.

like image 592
Gabo Cuadros Cardenas Avatar asked Apr 19 '16 22:04

Gabo Cuadros Cardenas


People also ask

How do I convert a string to JSON?

String data can be easily converted to JSON using the stringify() function, and also it can be done using eval() , which accepts the JavaScript expression that you will learn about in this guide.


1 Answers

Actually, there was a built-in function in SwifyJSON called parse

/**  Create a JSON from JSON string - parameter string: Normal json string like '{"a":"b"}'  - returns: The created JSON */ public static func parse(string:String) -> JSON {     return string.dataUsingEncoding(NSUTF8StringEncoding)         .flatMap({JSON(data: $0)}) ?? JSON(NSNull()) } 

Note that

var json = JSON.parse(stringJSON) 

its now changed to

var json = JSON.init(parseJSON:stringJSON) 
like image 111
HamGuy Avatar answered Oct 04 '22 03:10

HamGuy