我需要在下面的json中获取所有“students_id”值并将其存储在数组中。请告诉我有效的方法来执行此操作。请帮助。谢谢
{
"status": "success",
"user": [
{
"student_id": 1,
"first_name": "Student 1",
"last_name": "Student 1",
"emergency_contact_person": null,
"dob": "0000-00-00",
"class_section_id": 1,
"class_section_name": "A",
"class_id": 1,
"class_name": "10th"
},
{
"student_id": 2,
"first_name": "Student 2",
"last_name": "Student 2",
"emergency_contact_person": null,
"dob": "0000-00-00",
"class_section_id": 1,
"class_section_name": "A",
"class_id": 1,
"class_name": "10th"
}
],
"response": 200
}
答案 0 :(得分:0)
您始终可以使用user
循环并遍历for string["users"].each do |x| # => string has your PARSED json
return x["student_id"]
end
下的每个部分
ruby
代码是用{{1}}编写的,但您将基本了解该怎么做。
答案 1 :(得分:0)
您可以使用Codable
协议。如果您的JSON返回,只需创建一个镜像结构的结构:
struct Response: Codable {
let status: String
let user: [Student]
}
struct Student: Codable {
let student_id: Int
let first_name: String
let last_name: String
let emergency_contact_person: String?
let dob: String
let class_section_id: Int
let class_section_name: String
let class_id: Int
let class_name: String
}
从那里开始,您使用JSONDecoder
解码您的JSON,然后使用map
从中提取您需要的ID:
let jsonData = json.data(using: .utf8)
let decoder = JSONDecoder()
var studentIDs: [Int] = []
if let jsonData = jsonData {
do {
let responseStruct = try decoder.decode(Response.self, from: jsonData)
studentIDs = responseStruct.user.map{$0.student_id}
} catch {
print("\(error): \(error.localizedDescription)")
}
}
这是指向post re: decoding JSONs in Swift 4的链接。
如果您不需要JSON中的所有内容,那么您可以缩写结构来仅解析所需的元素。在此示例中,您可以将结构缩写为以下内容:
struct Response: Codable {
let user: [Student]
}
struct Student: Codable {
let student_id: Int
}