Reputation: 11
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)!)
}
Upvotes: 0
Views: 61
Reputation: 742
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] }
Upvotes: 1
Reputation: 372
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.
Upvotes: 0