1

I want the size value in json object but the problem is I'm getting whole json data i want only size value to print

here is my json

[{
   size = {
    height = 20
    width = 10
    },
    number = 100
}]

here is my code

     do{
            let Json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
            //print(Json as Any)

            guard let newValue = Json as? [[String: Any]] else {
                print("invalid format")
                return
            }
            print(newValue)

        }catch {
            print("Response Not Found.")
         }
6
  • You need to fetch size key only to print size. For reference follow this link stackoverflow.com/questions/40736924/… Commented Mar 8, 2019 at 11:19
  • can u write a code for me Commented Mar 8, 2019 at 11:20
  • 1
    My dear please try first and if you have any issue please let us know.... we will surely help you .... Commented Mar 8, 2019 at 11:22
  • I'm getting whole json data i want to only size value Commented Mar 8, 2019 at 11:23
  • Hey @username000, the model you are getting after parsing is array. You need to get to the index of that array first, then reach the key value pair. Your case will be newValue[<int index>]["Key"] or for trial you can do newValue.first["key"] Commented Mar 8, 2019 at 11:30

3 Answers 3

3

Please learn to read JSON, it's pretty easy, there are only two collection types:

  • [] is array, Swift [Any] but in almost all cases [[String:Any]], accessed with index subscription.
  • {} is dictionary, Swift [String:Any], accessed with key subscription

Never use the mutableContainers option in Swift, it has no effect at all.

if let json = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]] {
    for item in json {
        if let size = item["size"] as? [String:Any] {
            print(size["height"], size["width"])
        }
    }
}

And variable names are supposed to start with a lowercase letter.

PS: You have to cast the type of height and width. The output – which is actually not JSON – is ambiguous, you cannot see if the value is String or Int

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

2 Comments

What is (was?) the mutableContainers option supposed to do?
@Fehniix it’s a Objective-C related option to assign the result to an NSMutable… object which makes no sense in Swift. And it makes no sense anyway if the result is assigned to a let constant.
0

You just need to extract size from newValue . Try this

do  {
        let Json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
        guard let newValue = Json as? [[String: Any]],
            let size = newValue[0]["size"] as? [String:Any] else {
                return
        }
        print(size)
    }
    catch {
        print("Response Not Found.")
    }

Comments

-1
guard let newValue = Json as? [[String: Any]] else {
     print("invalid format")
     return
}
print(newValue["size"]) 

or if you want height & width

var sizeDict = newValue["size"] as! [String:Any]

print("Width - \(sizeDict["width"])")
print("Width - \(sizeDict["height"])")

5 Comments

im getting error Cannot subscript a value of type '[[String : Any]]' with an index of type 'String'
dictionary is present inside the array, newValue["size"] will be an error. You can correct your answer stating the same.
var sizeDict = newValue[0]["size"]
foreach statment
for dict in newValue { dict["size"] }

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.