如何从 iOS 中的 JSON 的子数组中读取数据

How to Read Data From a children array of a JSON in iOS

这是我的 json

let myjson = """
{
  "name": "md",
  "student": "cse",
  "project":[{
    "id": "1",
    "pname":"iOS"
  },{
    "id": "2",
    "pname":"adroid"
  }],
}
"""

从这个 json 我想在我的 swift playground 程序中打印特定数据

我只想打印这个数据

{
"id": "1",
"pname":"iOS"
} 

here is an image of what I tried

谢谢。

您可以解码您的 json 并编码为新的 json 字符串:

struct Response: Codable {
    var project: [Project]
}

struct Project: Codable {
    var id: String
    var pname: String
}

// your json string
let myjson = """
{ "name": "md", "student": "cse", "project":[{ "id": "1", "pname":"iOS" },{ "id": "2", "pname":"adroid" }]}
"""
let data = myjson.data(using: .utf8)!
let response = try! JSONDecoder().decode(Response.self, from: data)
   
// encode to print new json string
let encoded = try! JSONEncoder().encode(response)
let jsonString = String(data: encoded, encoding: .utf8)
print(jsonString)