how to get value from json array in swift4

Related searches

I can't getting json value into variable.I'm printing value but the problem is I can't getting json value without array

here is my json

{
"Categories": [
    "city",
    "delhi"
   ]
}

I want to categories value with array im printing value with array

here is my code

do{
            let json = try JSONSerialization.jsonObject(with: data!, options: []) as! [String: AnyObject]
            print(json as AnyObject)

            if let Categories = json["Categories"] {
                print(Categories)
            }

You need

 do {

     let json = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:[String]]
      let arr1 = json["Categories"]!
      let str1 =  arr1.joined(separator: ":")
       print(str1)
     // or 
      let decoded = try JSONDecoder().decode(Root.self, from: data)
       let str =  decoded.categories.joined(separator: ":")
       print(str)

 } catch {
     print(error)
 }

or use

struct Root: Codable {
    let categories: [String] 
    enum CodingKeys: String, CodingKey {
        case categories = "Categories"
    }
}

Working with JSON in Swift - Swift Blog, To get an Array value from a JSON array type, conditionally cast it as [Any] (or an array with a more specific element type, like [String]). You can extract a dictionary value by key or an array value by index using type cast optional binding with subscript accessors or pattern matching with enumeration. 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.

Make your life easier with Codable. First create custom model for your response

struct Response: Decodable {

    let categories: [String]

    enum CodingKeys: String, CodingKey {
        case categories = "Categories"
    }
}

Then decode your data which your receive using JSONDecoder

if let data = data {
    do {
        let decoded = try JSONDecoder().decode(Response.self, from: data)
        let string = decoded.categories.joined(separator: ", ") // if u need to join 
                                                                // your array to 
                                                                // single `String`
        print(string)
    } catch { print(error) }
}

Parsing Embedded JSON and Arrays in Swift, We can now parse JSON into our model objects using the <| and function is telling the <| operator to try and make the value associated to the To get an Array value from a JSON array type, conditionally cast it as [Any] (or an array with a more specific element type, like [String]). You can extract a dictionary value by key or an array value by index using type cast optional binding with subscript accessors or pattern matching with enumeration.

Use built in swift support for decoding json by conforming to Decodable and also conform to CustomStringConvertible to get a string representation of the values

struct Item: Decodable, CustomStringConvertible {
    let categories: [String]

    enum CodingKeys: String, CodingKey {
        case categories = "Categories"
    }

    public var description: String {
        return categories.joined(separator: " ")
    }
}

let decoder = JSONDecoder()
do {
    let result = try decoder.decode(Item.self, from: data)
    let descr = result.description
    print(descr)
} catch {
    print(error)
}

Simple JSON Parsing with Swift |, The typical output of such is a dictionary containing other dictionaries, arrays, numbers and. The first task is to generate a wrapped JSON value. Let's define a Swift 4 includes a new way to generate & parse JSON using the Codable protocol. It’ll get rid of some boilerplate, especially when the objects or structs in our code have a similar structure to the JSON that we use to talk to a web service.

//Model Class should be like this
struct JsonResposne : Codable {

    let categories : [String]?

    enum CodingKeys: String, CodingKey {
            case categories = "Categories"
    }

    init(from decoder: Decoder) throws {
            let values = try decoder.container(keyedBy: CodingKeys.self)
            categories = try values.decodeIfPresent([String].self, forKey: .categories)
    }

}

func getCategoriesResponse() {

Alamofire.request(requestUrl, method: .post, parameters: params, encoding: URLEncoding.default).responseJSON { (response) in
        switch response.result {
        case .success:
            if response.data != nil {
                do {
        let decoder = JSONDecoder()
        let apiResponse:JsonResponse = try decoder.decode(JsonResponse.self, from: responseData)
        print(apiResponse.categories.count)

    }catch {
        print(error.localizedDescription)
    }
                }
            }
            break
        case .failure:
            print("There was something with your call")
            break
        }
    }

}

Parsing JSON, JSON is a way of representing Arrays and Dictionaries of values ( String , Int , Float , Double ) as a text file. In a JSON file, Arrays are denoted by [ ] and Browse other questions tagged json swift4 swifty-json algorithmia or ask your own question. Blog Ben Popper is the worst coder in the world: Something awry with my array

How to parse JSON with Swift 3, If you're using Swift 4, head to How to parse JSON with Swift 4 — a lot has Here, we're taking the "blogs" from the JSON, casting that value to an array of Swift get values from JSON. to get the value of user_guid in the loop when there's only one and it's not in the same array as the entity_guid values

Technically, any value that’s serializable can be transformed or used in JSON. This includes base64 strings, numbers, objects, custom classes and structs, and so on.If you’re looking to use well-structured objects with JSON, i.e. individual books as opposed to networking responses, check out this article about Codable: Working With JSON And Codable In Swift.

Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.

Comments
  • try using swiftyjson via pods
  • its printing with array i want to display without array
  • its getting without array but i want to that value into variable