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.
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)
I fix it on this way.
I will use the variable "string" as the variable what contains the JSON.
1.
encode the sting with NSData like this
var encodedString : NSData = (string as NSString).dataUsingEncoding(NSUTF8StringEncoding)!
un-encode the string encoded (this may be sound a little bit weird hehehe):
var finalJSON = JSON(data: encodedString)
Then you can do whatever you like with this JSON.
Like get the number of sections in it (this was the real question) with
finalJSON.count or print(finalJSON[0]) or whatever you like to do.
There is a built-in parser in SwiftyJSON:
let json = JSON.init(parseJSON: responseString)
Don't forget to import SwiftyJSON!
I'm using as follows:
let yourString = NSMutableString()
let dataToConvert = yourString.data(using: String.Encoding.utf8.rawValue)
let json = JSON(data: dataToConvert!)
print("\nYour string: " + String(describing: json))
Swift4
let json = string.data(using: String.Encoding.utf8).flatMap({try? JSON(data: $0)}) ?? JSON(NSNull())
Related
So far I have this:
do{
let (responseString, _) = try await URLSession.shared.data(for: request)
if let decodedResponse = try? JSONDecoder().decode([Quote].self, from: responseString){
quotes = decodedResponse
}
}catch{
print("data not valid")
}
which instantly converts the json string to object array (quotes) but this is not what I need.
I need to parse each item and then add it to the object array like this:
quotes.append(Quote(quote_id: id, quote: qqq, author: aut, series: srs))
how to do that?
The only similar question I've found is
String convert to Json Array and then parse value in swift iOS?
but he doesn't have a json array but json object so the answers there aren't helping
Im stuck trying to model a JSON array which has no property name into my swift project with the goal of parsing the data and using it in my app. I know how to do this when there is a NAME for the array but I don't know how to make swift and this lackluster JSON understand each other. The path to the first "Company" in the JSON is "0.Company". The error I get is "Value of type 'WorkData' has no member '0'"
Im including pictures of my full project so it is easier to understand the structure of the code and what im trying to do. Please look at the picture for a clearer understanding I apologize if Im not explaining it well i'm new to programming.
import Foundation
class WorkData: Codable {
let WorkData: [WorkData]
let Company: String
let worklogDate: String
let issue: String
}
func parseData(jsonDataInput: Data) {
let decoder = JSONDecoder() // an object that decodes JSON data
do {
let decodedData = try decoder.decode(WorkData.self, from: jsonDataInput)
let Company = decodedData.0.Company
let worklogDate = decodedData.0.worklogDate
let issue = decodedData.0.issue
} catch {
print (error)
}
}
}
json
Trying to model JSON in Swift
Parsing JSON
You cannot start JSON with an array because JSON itself is an object {}
See example below:
{
"WorkData" : [
{"Company" : ""},
{"Company" : ""},
{"Company" : ""}
]
}
let decodedData = try decoder.decode(LocalizationsResponse.self, from: jsonDataInput)
decodedData will be an array
I'm attempting to print out a string array without escaped single quotes. For some reason, Swift is injecting escaped single quotes when printing my array. This has a trickle down problem when I use the array to build JSON. JSON ends up not being able to parse due to the escaped single quotes.
I thought this was a problem with my code, but I've distilled this down to a single usecase that should be straightforward.
let names = ["Tommy 'Tiny' Lister", "Tom Hanks"]
print(names)
The output is:
["Tommy \'Tiny\' Lister", "Tom Hanks"]
Note: I did not include escaped single quotes in my names array.
How do I prevent this from happening?
Here is the what I'm doing later in code to create JSON. For purposes of brevity, this is a really dumbed down version of what I'm doing:
var names = ["Tommy Tiny Lister", "Tom Hanks"]
var jsonString = """
{"names": \(names)}
"""
var jsonData = jsonString.data(using: .utf8)
if let json = try? JSONSerialization.jsonObject(with: jsonData!) as? [String: Any] {
let jsonData = try! JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
let string = String(data: jsonData, encoding: .utf8)
print(string!)
}
What you are doing is using Swift arrays' description to generate JSON:
var jsonString = """
{"names": \(names)}
""" // your JSON will contain name.description
You are relying on the fact that the implementation of description just so happens to result in the same format as JSON most of the time. As you can see, when there are ' in the array elements, the description is not valid JSON.
Basically, you should not rely on the description to generate JSON. Instead, you should use Codable to generate JSON data from a Swift array.
For the JSON you want to produce:
{
"names": ["Tommy 'Tiny' Lister", "Tom Hanks"]
}
You can use a struct like this:
struct Names : Codable {
let names: [String]
}
And then you can produce JSON Data like this:
let encoder = JSONEncoder()
do {
let obj = Names(names: ["Tommy 'Tiny' Lister", "Tom Hanks"])
let data = try encoder.encode(obj)
} catch { ... }
I am working on JSON parsing in Swift.
var results = [String:[AnyObject]]()
The above results is having the data as shown below,
"fruit" = (
"apple",
"orange"
);
Here, data is appended dynamically during runtime. All I need is to get the keys and display them in table view as header.
How to get thekey from results in swift?
NSJSONSerialization code example...
var results = [String:[AnyObject]]()
let jsonResult = try NSJSONSerialization.JSONObjectWithData(results, options:NSJSONReadingOptions.MutableContainers);
for (key, value) in jsonResult {
print("key \(key) value2 \(value)")
}
You can convert JSON to dictionary as mentioned in the above link proposed by Birendra. Then suppose jsonDict is your json parsed dictionary. Then you can get collection of all keys using jsonDict.keys.
You need to use NSJSONSerialization class to convert in json format (eg. to convert in dictionary) and then get all keys from it.
I have used,
var results = [String:Array<DataModel>]
where,
class DataModel {
var name: String?
}
and to fetch the keys and value,
for i in 0...(results.length-1){
// To print the results keys
print(results.keys[results.startIndex.advancedBy(i)])
// To get value from that key
let valueFromKeyCount = (results[results.keys[results.startIndex.advancedBy(i)]] as Array<DataModel>).count
for j in 0...(valueFromKeyCount-1) {
let dm = results[results.keys[results.startIndex.advancedBy(i)]][j] as DataModel
print(dm.name)
}
}
Tested with Swift 4.2 to get first key or list of keys:
This "one-liner" will return the first key, or only key if there is only one.
let firstKey: String = (
try! JSONSerialization.jsonObject(
with: data,
options: .mutableContainers
) as! [String: Any]).first!.key
This one will get a list of all the keys as and array of Strings.
let keys: [String] = [String] ((
try! JSONSerialization.jsonObject(
with: data,
options: .mutableContainers
) as! [String: Any]).keys)
Both of the above examples work with a JSON object as follows
let data = """
{
"fruit" : ["apple","orange"],
"furnature" : ["bench","chair"]
}
""".data(using: .utf8)!
How can I parse that json array ,which is string format with using Swift ? I was doing by hand like removing brackets and splitting text by commas etc. But algorithm goes wrong if any of array elements has comma inside like ("DEF1,23") . So is there any predefined library from Apple to do that ?
Note : I saw some solutions in stackoverflow but that functions takes inputs which is NSData formatted so, I need string implementation of that parsing functions.
var jsonstring : String = "["ABC123","DEF1,23","ASD54,21"]"
let str: NSString = /* json string */
var error: NSError?
if let data = NSJSONSerialization.JSONObjectWithData(str.dataUsingEncoding(NSUTF8StringEncoding)!, options: nil, error: &error) as? NSArray {
println(data)
}