0

I am trying to get value from a json file but it returns null.

Here is the code:

     Alamofire.request( jsonUrl).responseJSON { (responseData) -> Void in
        if((responseData.result.value) != nil) {


            let swiftyJsonVar = JSON(responseData.result.value!)["value"]
            print(swiftyJsonVar)
            let temp = swiftyJsonVar["value"]
            print(temp)
        }
    }

Here is the output from swiftyJsonVar:

[
  {
    "value" : "13.1",
    "quality" : "G",
    "date" : 1564772400000
  }
]

And the output from temp is null.

Why is temp null and not 13.1?

1
  • 1
    Use JSON(responseData.result.value!)[0]["value"] Commented Aug 3, 2019 at 20:02

1 Answer 1

2

This will be an array: responseData.result.value

The array contains a dictionary with a key named value

So you should take first element of the array and then take the value of the value key like this:

JSON(responseData.result.value!)[0]["value"]

- A better way to work with a JSON:

Take a look at Codable. This is much better way to deal with json.

with Codable you first define your object:

struct MyDTO {
    let value: String,
    let quality: String,
    let date: Int // or any type you need
}

Then you decode it with a JSONDecoder:

let results = try! JSONDecoder().decode([MyDTO].self, from: responseData)

and lastly you can access your needed item like this:

results.first!.value

Remember to handle ! in a proper way.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.