Answer the question
In order to leave comments, you need to log in
Why is each iteration of the for loop of a JSON object a string?
for item in data {
print(item)
}
("0", {
"title" : "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"userId" : 1,
"id" : 1,
"body" : "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
})
("1", {
"title" : "qui est esse",
"userId" : 1,
"id" : 2,
"body" : "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
})
("2", {
"title" : "ea molestias quasi exercitationem repellat qui ipsa sit aut",
"userId" : 1,
"id" : 3,
"body" : "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
})
("3", {
"title" : "eum et est occaecati",
"userId" : 1,
"id" : 4,
"body" : "ullam et saepe reiciendis voluptatem adipisci\nsit amet autem assumenda provident rerum culpa\nquis hic commodi nesciunt rem tenetur doloremque ipsam iure\nquis sunt voluptatem rerum illo velit"
})
Answer the question
In order to leave comments, you need to log in
your data is not JSON (whatever you mean by that), your data is an array of strings ([String]).
In general, JSON is a string, when you receive JSON from a network response, you convert this string into some kind of object (most often an Array or Dictionary), and then iterate over these objects. It's impossible to iterate through a string unless it's over characters (Characters).
If swift 4, create objects:
struct Container: Decodable {
let messages : [Message]
}
struct Message : Decodable {
private enum CodingKeys : String, CodingKey {
case userId
case id
case title
case body
}
let userId, id: Int
let title, body: String
}
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
decoder.decode(Container.self, from: data)
// здесь data это Data
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question