Reputation: 123
I am trying to convert some json data which i receive from a get request into a usable array or something like this
the json data i recieve looks like this
{
"elementlist":{
"Ready Position":{
"Neutral Grip":["1,2,3,4,5"],"
Back Straight (Concave ir Convex?)":["1,2,3,4,5"],"
Body Low & Feet a little more than sholder width apart":["1,2,3,4,5"],"
Weight on Balls of Feet":["1,2,3,4,5"],"
Head Up":["1,2,3,4,5"],"
Sholder Blades Close":["1,2,3,4,5"],"
Eyes Drilled":["1,2,3,4,5"]
},
"Split Step":{"
Ready Position Conforms":["Yes,No"],"
Body Position Low":["1,2,3,4,5"],"
Legs Loaded/Prepared":["1,2,3,4,5"]
}
}
}
this is the swift i am using
let playerAPIurl = "http://linkcoachuat.herokuapp.com/api/v1/session/element?organisation=5&group=green&sport=tennis"
var request = URLRequest(url: URL(string: playerAPIurl)!)
request.httpMethod = "GET"
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request) { (data, response, error) in
if error != nil {
print("ERROR")
}
else{
do{
print("hello")
let myJson = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any]
// Convert myJson into array here
print(myJson)
}
catch
{
}
}}
What i would like to be able to do is get an array of the names of the nested arrays so elementarray = ["Ready Position","Split Step"] and then be able to access the arrays by saying myJson[elementarray[0]] or something similar
im a bit of a swift noob so any help is appreciated please try and explain the answers so they are easily understood
thank you for any help
Upvotes: 1
Views: 512
Reputation: 1433
You can try to downcast that json same way you've already made:
let myJson = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any]
//creating the new array of additional elements
let elementArray: [[String: Any]] = []
//making myJson parsing for additional items
if let readyPosition = myJson?["Ready Position"] as? [String: Any] {
elementArray.append(readyPosition)
}
if let splitStep = myJson?["Split Step"] as? [String: Any] {
elementArray.append(splitStep)
}
make print(elementArray) to be sure that all was parsed correctly.
Honestly, I prefer to use objects (custom classes or structs) to store values and have an ability to make related instances or values, but up to you
Upvotes: 3