Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftyJSON looping through an array of JSON objects

[
    {
        "cont": 9714494770,
        "id": "1",
        "name": "Kakkad"
    },
    {
        "cont": 9714494770,
        "id": "2",
        "name": "Ashish"
    }
]

The one above is a json array filled with JSON objects. I don't know how to parse through this with SwiftyJSON

like image 734
gwhiz Avatar asked Apr 20 '15 20:04

gwhiz


People also ask

Is looping an array is possible in JSON?

Looping Using JSON JSON stands for JavaScript Object Notation. It's a light format for storing and transferring data from one place to another. So in looping, it is one of the most commonly used techniques for transporting data that is the array format or in attribute values.

Can you have an array of objects in JSON?

A JSON array contains zero, one, or more ordered elements, separated by a comma. The JSON array is surrounded by square brackets [ ] . A JSON array is zero terminated, the first index of the array is zero (0). Therefore, the last index of the array is length - 1.

Can JSON array heterogeneous?

Each item in a JSON array may be any type of JSON value. This is called a heterogeneous array. Typically an array contains only one type of value, such as an array of strings.

What is the difference between JSONObject and JSONArray?

JSONObject and JSONArray are the two common classes usually available in most of the JSON processing libraries. A JSONObject stores unordered key-value pairs, much like a Java Map implementation. A JSONArray, on the other hand, is an ordered sequence of values much like a List or a Vector in Java.


2 Answers

Assuming [{"id":"1", "name":"Kakkad", "cont":"9714494770"},{"id":"2", "name":"Ashish", "cont":"9714494770"}] is assigned to a property named jsonData.

let sampleJSON = JSON(data: jsonData)

let sampleArray = sampleJSON.array sampleArray is an optional array of JSON objects.

let firstDict = sampleArray[0] firstDict is an optional JSON dict.

let name = firstDict["name"] is an optional JSON object

let virtName = name.string is a optional string (In this case "Kakkad").

let realName = name.stringValue realName is a string or an empty string.

You could also use: let longName = sampleJSON[0]["name"].stringValue

After you initialize the JSON object with data all of the elements are JSON types until you convert them to a swift type.

  • .string optional (string or null)
  • .stringValue string or "" empty string
  • .dict optional ([String: AnyObject] or null)
  • .dictValue ([String: AnyObject] or String: AnyObject)
like image 137
adamek Avatar answered Oct 21 '22 12:10

adamek


Example from the SwiftyJSON page, adapted to your data:

let json = JSON(data: dataFromNetworking)
for (index, object) in json {
    let name = object["name"].stringValue
    println(name)
}
like image 22
Eric Aya Avatar answered Oct 21 '22 12:10

Eric Aya