gpt4 book ai didi

json - 解析本地json文件

转载 作者:行者123 更新时间:2023-11-28 10:57:50 25 4
gpt4 key购买 nike

我有这个 JSON 文件:

{
"People" : [{
{
"Name": "Jack"
"Age": 130,
"Job": "Doctor",
},
{
"Name": "Mark"
"Age": 45,
"Job": "Engineer",
},
{
"Name": "Sarah"
"Age": 27,
"Job": "Designer",
},

}]
}

下面是我如何使用辅助函数解析它:

static func parseJson(file: String) -> [String: Any] {
let jsonFile = Bundle.main.path(forResource: file, ofType: "json")
let jsonData = NSData(contentsOfFile: jsonFile!)
let jsonDictionary = try? JSONSerialization.jsonObject(with: jsonData! as Data, options: [])

return jsonDictionary as! [String: Any] <-- Error
}

然后当我尝试初始化它时:

let data = parseJson(file: "People")  as! [String: Any]
print(data["people"])

我收到这个错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

我在这里做错了什么?我跟着这个tutorial by Apple

最佳答案

始终使用一些验证器来验证您的 JSON。

http://jsonviewer.stack.hu/

正确的JSON格式:

{
"People" : [
{
"Name": "Jack",
"Age": 130,
"Job": "Doctor",
},
{
"Name": "Mark",
"Age": 45,
"Job": "Engineer",
},
{
"Name": "Sarah",
"Age": 27,
"Job": "Designer",

}]
}

关于json - 解析本地json文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42170416/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com