How to parse Array of JSON to array in Swift - ios

I'm trying to parse JSON which is like below
[
{
"People": [
"Jack",
"Jones",
"Rock",
"Taylor",
"Rob"
]
},
{
"People": [
"Rose",
"John"
]
},
{
"People": [
"Ted"
]
}
]
to an array which results in:
[ ["Jack", "Jones", "Rock", "Taylor", "Rob"] , ["Rose", "John"], ["Ted"] ]
which is array of arrays.
I tried with code below
if let path = Bundle.main.path(forResource: "People", ofType: "json") {
let peoplesArray = try! JSONSerialization.jsonObject(
with: Data(contentsOf: URL(fileURLWithPath: path)),
options: JSONSerialization.ReadingOptions()
) as? [AnyObject]
for people in peoplesArray! {
print(people)
}
}
when I print "people" I get o/p as
{
People = (
"Jack",
"Jones",
"Rock",
"Taylor",
"Rob"
);
}
{
People = (
"Rose",
"John"
);
}
...
I'm confused how to parse when it has "People" repeated 3 times
Trying to display content in UITableView where my 1st cell has "Jack" .."Rob" and Second cell has "Rose" , "John" and third cell as "Ted"
PLease help me to understand how to achieve this

You can do this in an elegant and type safe way leveraging Swift 4 Decodable
First define a type for your people array.
struct People {
let names: [String]
}
Then make it Decodable, so that it can be initialised with a JSON.
extension People: Decodable {
private enum Key: String, CodingKey {
case names = "People"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Key.self)
self.names = try container.decode([String].self, forKey: .names)
}
}
Now you can easily decode your JSON input
guard
let url = Bundle.main.url(forResource: "People", withExtension: "json"),
let data = try? Data(contentsOf: url)
else { /* Insert error handling here */ }
do {
let people = try JSONDecoder().decode([People].self, from: data)
} catch {
// I find it handy to keep track of why the decoding has failed. E.g.:
print(error)
// Insert error handling here
}
Finally to get get your linear array of names you can do
let names = people.flatMap { $0.names }
// => ["Jack", "Jones", "Rock", "Taylor", "Rob", "Rose", "John", "Ted"]

var peoplesArray:[Any] = [
[
"People": [
"Jack",
"Jones",
"Rock",
"Taylor",
"Rob"
]
],
[
"People": [
"Rose",
"John"
]
],
[
"People": [
"Ted"
]
]
]
var finalArray:[Any] = []
for peopleDict in peoplesArray {
if let dict = peopleDict as? [String: Any], let peopleArray = dict["People"] as? [String] {
finalArray.append(peopleArray)
}
}
print(finalArray)
output:
[["Jack", "Jones", "Rock", "Taylor", "Rob"], ["Rose", "John"], ["Ted"]]
In your case, it will be:
if let path = Bundle.main.path(forResource: "People", ofType: "json") {
let peoplesArray = try! JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: path)), options: JSONSerialization.ReadingOptions()) as? [Any]
var finalArray:[Any] = []
for peopleDict in peoplesArray {
if let dict = peopleDict as? [String: Any], let peopleArray = dict["People"] as? [String] {
finalArray.append(peopleArray)
}
}
print(finalArray)
}

let assume that the json is the encoded data
var arrayOfData : [String] = []
dispatch_async(dispatch_get_main_queue(),{
for data in json as! [Dictionary<String,AnyObject>]
{
let data1 = data["People"]
arrayOfData.append(data1!)
}
})
You can now use the arrayOfData. :D

what you have here is first an array of 3 objects. each object is a dictionary where the key is people and the value is an array of strings. when you're trying to do jsonserialization, you have to cast it down to the expected result. So you have first an array of objects, then you have a dictionary with String: Any, then you obtain an array of String
let peoplesArray = try! JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: path)), options: []) as? [AnyObject]
guard let peoplesObject = peoplesArray["people"] as? [[String:Any]] else { return }
for people in peoplesObject {
print("\(people)")
}

I couldn't pasted it in a comment, it is too long or something
static func photosFromJSONObject(data: Data) -> photosResult {
do {
let jsonObject: Any =
try JSONSerialization.jsonObject(with: data, options: [])
print(jsonObject)
guard let
jsonDictionary = jsonObject as? [NSObject: Any] as NSDictionary?,
let trackObject = jsonDictionary["track"] as? [String: Any],
let album = trackObject["album"] as? [String: Any],
let photosArray = album["image"] as? [[String: Any]]
else {
return .failure(lastFMError.invalidJSONData)
}
}
}
And the json was something like:
{
artist: {
name: Cher,
track: {
title: WhateverTitle,
album: {
title: AlbumWhatever,
image: {
small: "image.px",
medium: "image.2px",
large: "image.3px"}
....

Related

Fetch value of dictionary from JSON

I want to fetch values of string from JSON , I am able to parse JSON to Dictionary but not able to convert into array of string
FROM SERVER
{
“ALL TEXT: [
{
"text": "hello"
},
{
"text": "hi"
},
{
"text": "how r u"
}
]
}
I only want value of text to append to my string array "textsList"
var textsList : [String]()
This is what I had tried
URLSession.shared.dataTask(with: request) { (data, response, err) in
let json = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! Dictionary<String, Any>
let AllText = json[“ALL TEXT”] as! [Dictionary<String, Any>]
let value = JSON(AllText)
AllText.forEach { fetch in
self.textsList.append(fetch.values) // ERROR no exact matches in call to instance method append
}
for(key, object) in value{
print(value) //output: {"text": "hello" },{"text": "hi" }
print(value.string) //output:nil
}
}.resume()
I just want to convert dictionary into array , but also alternate solution to convert JSON directly into array of string will be fine.
Adjust the code:
let string = """
{
"ALL TEXT": [
{
"text": "hello"
},
{
"text": "hi"
},
{
"text": "how r u"
}
]
}
"""
guard let data = string.data(using: .utf8),
let json = try? JSONSerialization.jsonObject(with: data, options: []) as? Dictionary<String, Any>,
let allText = json["ALL TEXT"] as? [Dictionary<String, Any>]
else {
DDLog("json fail")
return }
DDLog(allText) // [["text": hello], ["text": hi], ["text": how r u]]
let items: [String] = allText.compactMap { $0["text"] as? String }
var textsList = [String]()
textsList.append(contentsOf: items)
DDLog(items) //["hello", "hi", "how r u"]
DDLog(textsList) //["hello", "hi", "how r u"]
Two errors:
1. <"ALL TEXT> Missing right quote;
2. var textsList: [String]() =》var textsList = [String]();

Fetch and Check internal (Local) JSON file in swift

I want to check city name From local JSON if found then massage show "You got it". But one problem came occurred that is I fetch data from file is successfully but I'd know how to compare it.
Here is my JSON file look like:
{
"data": [
{
"zip_code": 55001,
"latitude": 44.90717,
"longitude": -92.816193,
"city": "Afton",
"state": "MN",
"county": "Washington"
},
{
"zip_code": 55002,
"latitude": 45.513447,
"longitude": -92.894239,
"city": "Almelund",
"state": "MN",
"county": "Chisago"
}
]
}
Code is here:
func FatchingInformation(){
do {
if let file = Bundle.main.url(forResource: "Zone", withExtension: "json") {
let data = try Data(contentsOf: file)
let json = try JSONSerialization.jsonObject(with: data, options: [])
if let object = json as? [String: Any] {
// This condition work and Get JSON on Debug Area
print("Obj is ::: \(object)")
} else if let object = json as? [Any] {
// json is an array
print("Object is \(object)")
} else {
print("JSON is invalid")
}
} else {
print("no file")
}
} catch {
print(error.localizedDescription)
}
}
you are in right way on your JSON is dict of array of dictionary, you need to iterate your [String: Any] first there after check it contains array or dict then you need to follow as below
if let object = json as? [String: Any], let objectArray = object["data"] as? [[String: Any]] {
// do stuff
for getDictItems in objectArray{
if let getCityCompare = getDictItems["city"] as? String, !getCityCompare.isEmpty, getCityCompare == "Almelund"{
print("city name is \(getCityCompare)")
break
}
}
}
You ca use decodable Struct to decode json
// MARK: - Address
struct Address: Codable {
let data: [Datum]
}
// MARK: - Datum
struct Datum: Codable {
let zipCode: Int
let latitude, longitude: Double
let city, state, county: String
enum CodingKeys: String, CodingKey {
case zipCode = "zip_code"
case latitude, longitude, city, state, county
}
}
let address = try? JSONDecoder().decode(Address.self, from: jsonData)

Swift: Convert object to Dictionary not working properly

I'm trying to convert an object to NSDictionary with an extension. It works fine but if the object contains an array, then the array does not convert to NSDictionary but to Json and that is not what I want. Because I try with this Dictionary to make a request post and the body accepts [String: Any].
My code:
struct Country: Codable {
let name: String
let cities: [City]
struct City: Codable {
let name: String
}
}
extension NSDictionary {
func encode<T>(_ value: T) throws -> [String: Any]? where T: Encodable {
guard let jsonData = try? JSONEncoder().encode(value) else { return nil }
return try? JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as? [String: Any]
}
}
Using:
let country = Country(name: "France", cities: [Country.City(name: "Paris"), Country.City(name: "Marseille")])
print(try! NSDictionary().encode(country))
Output:
["name": France, "cities": <__NSArrayI 0x600002926e60>(
{
name: "Paris",
},
{
name: "Marseille",
})
]
Expected output (what I want):
["name": France, "cities": [
[
"name": Paris,
],
[
"name": Marseille,
]
]
]
The output is correct since your result is NSDictionary and the output is the string representation (aka description) of NSDictionary. <__NSArrayI 0x600002926e60> is syntactic sugar.
By the way the expected output is invalid because the city names must be in double quotes.
The extension of NSDictionary makes no sense anyway. If you want to be able to call the method from everywhere declare a struct with a static method.
This is a swiftier version of your code. No allowFragments and all errors are thrown rather than being ignored.
struct DictionaryEncoder {
static func encode<T>(_ value: T) throws -> [String: Any] where T: Encodable {
let jsonData = try JSONEncoder().encode(value)
return try JSONSerialization.jsonObject(with: jsonData) as? [String: Any] ?? [:]
}
}
Copy the method and your structs into a Playground and run
let country = Country(name: "France", cities: [Country.City(name: "Paris"), Country.City(name: "Marseille")])
try! DictionaryEncoder.encode(country)
Don't print the result, look at the result area in the Playground, the output is exactly what you want.
You need
let res = try! JSONEncoder().encode(country)
print(res.prettyPrintedJSONString!)
extension Data {
var prettyPrintedJSONString: NSString? { /// NSString gives us a nice sanitized debugDescription
guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
let prettyPrintedString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) else { return nil }
return prettyPrintedString
}
}
Result
{
"name" : "France",
"cities" : [
{
"name" : "Paris"
},
{
"name" : "Marseille"
}
]
}

How can I decode JSON with array and more JSON inside?

I recently began with swift. I need decode the json on below.
The JSON has inside two more JSON the first one (validation) does not matter. The second one (result) has a JSON array inside (serviceCenter). I need the information of each servicenter. I try to use servicecenter as decodeable class to get a servicenter object, but as the JSON does not have the proper format I can't do it.
[
{
"validation": {
"bValid": true,
"sDescription": "Access true."
}
},
{
"result": {
"serviceCenter": [
{
"model": "Vanquish",
"color": "Purple",
"make": "Aston Martin",
"sTag": "3666",
"sVin": "6JDO2345",
"sMiles": "3666",
"bDamage": "1",
"dDateTime": "04-17-2018 9:38 AM"
},
{
"model": "F360",
"color": "Red",
"make": "Ferrari",
"sTag": "0010",
"sVin": "6JDO2347",
"sMiles": "80000",
"bDamage": "1",
"dDateTime": "04-17-2018 9:25 AM"
},
{
"model": "Vanquish",
"color": "Purple",
"make": "Aston Martin",
"sTag": "0009",
"sVin": "6JDO2345",
"sMiles": "25000",
"bDamage": "1",
"dDateTime": "04-17-2018 9:23 AM"
},
{
"model": "Vanquish",
"color": "Purple",
"make": "Aston Martin",
"sTag": "0003",
"sVin": "6JDO2345",
"sMiles": "20000",
"bDamage": "1",
"dDateTime": "04-12-2018 10:37 AM"
}
]
}
}
]
I try so much but i cant do it.
This its my code now, Could someone help me please
do {
let parseoDatos = try JSONSerialization.jsonObject(with: data!) as! [AnyObject]
let h = type(of: parseoDatos )
print("'\(parseoDatos)' of type '\(h)'")
let contenido = parseoDatos[1]["result"]
if let services = contenido!! as? Dictionary<String, Array<Any>> {
for (_,serviceArray) in services {
for sc in serviceArray{
let h = type(of: sc )
print("'\(sc)' of type '\(h)'")
}
}
}
} catch {
print("json processing failed")
}
the result of print sc is
{
bDamage = 1;
color = Purple;
dDateTime = "04-17-2018 9:38 AM";
make = "Aston Martin";
model = Vanquish;
sMiles = 3666;
sTag = 3666;
sVin = 6JDO2345;
}' of type '__NSDictionaryI'
You can use Codable
Initial response have array of InitialElement and InitialElement is is struct with validation , result , result may be nil
don't forget to add your URL at url
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if let initial = try? JSONDecoder().decode([InitialElement].self, from: data){
// inital now have array of InitialElement and InitialElement is is struct with validation , result , result may be nil
print(initial)
}
}.resume()
With this Model for Data:
import Foundation
struct InitialElement: Codable {
let validation: Validation?
let result: ResultData?
}
struct ResultData: Codable {
let serviceCenter: [ServiceCenter]
}
struct ServiceCenter: Codable {
let model, color, make, sTag: String
let sVin, sMiles, bDamage, dDateTime: String
}
struct Validation: Codable {
let bValid: Bool
let sDescription: String
}
extension InitialElement {
init(data: Data) throws {
self = try JSONDecoder().decode(InitialElement.self, from: data)
}
}
try this code
enum ParsingError: Error {
case wrongFormat(String)
}
do {
let jsonObject = try JSONSerialization.jsonObject(with: data!)
guard let array = jsonObject as? [Any] else {
throw ParsingError.wrongFormat("wrong root object")
}
guard array.count == 2 else {
throw ParsingError.wrongFormat("array count != 2")
}
guard let dict = array[1] as? [String: Any] else {
throw ParsingError.wrongFormat("can't parse dict from array")
}
guard let serviceCenters = (dict["result"] as? [String: Any])?["serviceCenter"] else {
throw ParsingError.wrongFormat("can't parse serviceCenters")
}
guard let serviceCentersArray = serviceCenters as? [[String : Any]] else {
throw ParsingError.wrongFormat("serviceCenters is not an array")
}
print("\(type(of: serviceCentersArray))\n", serviceCentersArray)
} catch {
print("json processing failed: \(error)")
}
Thanks all for yours answers, it's my first question here, and i feels great all the help. Finally i can resolve the problem. Maybe not the best way, but here its the code:
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil{
print("error=\(String(describing: error))")
return
}
do {
let parseoDatos = try JSONSerialization.jsonObject(with: data!) as! [AnyObject]
let h = type(of: parseoDatos )
print("'\(parseoDatos)' of type '\(h)'")
let contenido = parseoDatos[1]["result"]
if let services = contenido!! as? Dictionary<String, Array<Any>> {
for (_,serviceArray) in services {
for sc in serviceArray{
let h = type(of: sc )
print("'\(sc)' of type '\(h)'")
let valid = JSONSerialization.isValidJSONObject(sc) // true
print(valid)
do {
let jsonData = try JSONSerialization.data(withJSONObject: sc, options: .prettyPrinted)
let serviceDecoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
if let scJSON = serviceDecoded as? [String:String] {
print ("--------------------------")
print("'\(scJSON)' of type '\(type(of: scJSON))'")
print ("--------------------------")
}
} catch {
print(error.localizedDescription)
}
i think later y try to use Codable as suggested, but for now the code is working ok. Thanks again!
//try this it is working
let arrayMain=try?JSONSerialization.jsonObject(with:jsonData!,options:.mutableLeaves) as! Array<Any>
//print(arrayMain!)
if let firstDictionart=arrayMain![0] as? [String: Any] {
if let insideFirstDict = firstDictionart["validation"] as? [String: Any]{
print(insideFirstDict["bValid"]!)
print( insideFirstDict["sDescription"]!)
}
}
if let resultDictionary=arrayMain![1] as? [String: Any] {
if let serviceDictionary = resultDictionary["result"] as? [String: Any] {
for array in serviceDictionary["serviceCenter"] as! Array<Any>{
if let infoDicti=array as? [String: Any] {
print( infoDicti["color"]!)
print( infoDicti["make"]!)
print( infoDicti["color"]!)
print( infoDicti["sTag"]!)
print( infoDicti["sVin"]!)
print( infoDicti["sMiles"]!)
print( infoDicti["sVin"]!)
print( infoDicti["model"]!)
print( infoDicti["bDamage"]!)
print( infoDicti["dDateTime"]!)
}
}
}
}

how to get the JSONArray from jsonObject in Swift 3.1

{
"status": true,
"status_code": 1,
"content": [
{
"cat_id": "3",
"cat_name": "Food",
"cat_parentid": "2"
},
{
"cat_id": "4",
"cat_name": "Entertainment",
"cat_parentid": "2"
},
{
"cat_id": "5",
"cat_name": "Cars",
"cat_parentid": "2"
},
{
"cat_id": "12",
"cat_name": "Personal Care",
"cat_parentid": "2"
}
],
"message": "Success"
}
UPDATE
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
completion((json as? AnyObject)!) //here completion callback will return the jsonObject to my UIViewController.
}
} catch let error {
print(error.localizedDescription)
}
this is my JSONObject. I am very new to the swift. how to get the content JSONArray and further process in swift.? Anybody can help me? Help will be appreciated.
This code checks if the status is true, gets the array for key content and prints all values in the array.
The array is clearly [[String:String]] so cast the object to this specific type.
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
if let status = json["status"] as? Bool, status == true {
if let content = json["content"] as? [[String:String]] {
for category in content {
let id = category["cat_id"]
let name = category["cat_name"]
let parentId = category["cat_parentid"]
print(id , name, parentId)
}
}
}
}
} catch let error {
print(error.localizedDescription)
}
PS: As always, never use .mutableContainers in Swift. It's meaningless
Check whether your json has content array
if let content = json["content"] as? [Dictionary<String, AnyObject>] {
print(content) // it will give you content array
}
Get content array like this:
let allContent = json["content"] as? [[String: Any]]
Full sample:
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
if let allContent = json["content"] as? [[String: Any]] {
for content in allContent {
let catId = content["cat_id"] as? String
let catName = content["cat_name"] as? String
let catParentId = content["cat_parentid"] as? String
print(">> catid=" + catId!)
print(">> catName=" + catName!)
print(">> catparentID=" + catParentId!)
}
}
}
} catch let error {
print(error.localizedDescription)
}
let content = dict.objectForKey("content")! as NSArray
Then you can get json of single object for parsing by
for var cat in content
{
print(cat)
}
Another alternative way, by using the library.
First, import JSON library for Swift - SwiftyJSON and use the code:
import SwiftyJSON
let json = JSON(<jsonObject data>)
let contentArray: Array<JSON> = json["content"].arrayValue
Library Integration
If you're using cocoapods then use this pod:
pod 'SwiftyJSON'
OR else just drag SwiftyJSON.swift to the project tree.
you can extract you data by providing key
if let array = result["content"] as? Array<AnyObject> {
print(arry)
}
You can access like below
if let filePath = Bundle.main.path(forResource: "sample", ofType: "json"), let data = FileManager().contents(atPath: filePath) {
do {
let dicRes = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any]
let contentArray = dicRes?["content"]
print("contentArray == \(contentArray)")
} catch {
}
}

Resources