0
subject_id=[{"program_id": "1","subject_id":"1"},{"program_id":%20"2","subject_id":"5"}]

I Want to make this type of json.

This is my code i am trying to change subject_id only but it prints whole array. how can i change it.

let subject_id = [String](arrayLiteral: "1","5")

let program_id = [String](arrayLiteral: "1","3")

for program_id in program_id
        {
            print(program_id)
        }

        let phoneNumbersDictionary = program_id.map({ ["program_id": $0 , "subject_id" : $0 ] })


        let JSON = try? JSONSerialization.data(withJSONObject: phoneNumbersDictionary, options: [])

        if let JSON1 = JSON
        {
            print(String(data: JSON1, encoding: String.Encoding.utf8)!)
        }

2 Answers 2

1

If you want to use map, zip the 2 arrays before. Here is the working snippet

let pNumbers = zip(subject_ids, program_ids).map { s_id, p_id in ["subject_id": s_id, "program_id": p_id] }

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

Comments

0

For-in would be easier:

var index = 0
for pid in program_id {
    array.append(["program_id": pid, "subject_id": subject_id[index]])
    index = index + 1
}

If you really want to use map:

let phoneNumbersDictionary = program_id.map({ ["program_id": $0 , "subject_id" : subject_id[program_id.index(of: $0)!]]})

But I'd like to avoid the force unwrap.

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.