2

I'm having trouble creating a specific structure in JSON with Swift. I use Swifty JSON for parsing but I can't figure out how to create one.

I have this array which is filled by Id's and quantity Ints of products in a shopping basket . I need to get the array into my JSON but I don't know how.

If you could help me with this I would be very glad :)

    var productArray = Array<(id: Int,quantity: Int)>()

    let jsonObject: [String: AnyObject] = [
        "order": 1,
        "client" : 1,
        "plats": [
            for product in productArray
            {
            "id": product.id
            "quantity": product.quantity
            }
        ]
    ]
4
  • Is this code compiling ? Commented May 21, 2015 at 14:02
  • Nope, just "Expected expression in container literal" at the for line, I can't figure out how to do this Commented May 21, 2015 at 14:04
  • 1
    You've got a for loop [ and ], that's definitely not allowed. What did you want the value of they plats key to be? Commented May 21, 2015 at 14:12
  • I want to have "plats" who looks like puu.sh/hVinh/39d4e4e11c.png ! You know like an Array inside Commented May 21, 2015 at 14:14

2 Answers 2

1

You can't just start looping through stuff while defining your dictionary. Here's another approach.

First, create your array:

var productArray = Array<(id: Int,quantity: Int)>()

Add some products (for testing):

productArray += [(123, 1000)]
productArray += [(456, 50)]

Map this array into a new array of dictionaries:

let productDictArray = productArray.map { (product) -> [String : Int] in
    [
        "id": product.id,
        "quantity": product.quantity
    ]
}

Use the new mapped array in your JSON object:

let jsonObject: [String: AnyObject] = [
    "order": 1,
    "client" : 1,
    "plats": productDictArray
]
Sign up to request clarification or add additional context in comments.

Comments

1

You are not supposed to do any kind of looping/condition making block of codes while creating Array's or Dictionary. For that you need to execute that piece of code outside, create a variable and use it.

Do try this way.

var productArray = Array<(id: Int,quantity: Int)>()

    var prods = [[String:Int]]()
    for product in productArray
    {
        var eachDict = [String:Int]()
        eachDict["id"] =  product.id
        eachDict["quantity"] = product.quantity
        prods.append(eachDict)
    }

    let jsonObject: [String: AnyObject] = [
        "order": 1,
        "client" : 1,
        "plats": prods
    ]

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.