【问题标题】:Extracting a specific part from JSON从 JSON 中提取特定部分
【发布时间】:2018-08-04 06:02:55
【问题描述】:

您好,我正在尝试仅从 JSON 中提取 id 值。但是,如果我

print(response!["id"])

result = "未创建" 被输出。响应已经是 JSON 格式。 有什么我做错了吗?

更新 1

[

    {
        "user" : {
          "last_name" : "test",
          "email" : "test@test.com",

        },
        "id" : 902,
        "scale" : 7,
        "created_at" : "2018-02-24 06:45:33",
      },
  {
        "user" : {
          "last_name" : "test",
          "email" : "test@test.com",

        },
        "id" : 903,
        "scale" : 7,
        "created_at" : "2018-02-24 06:45:33",
      },
  {
        "user" : {
          "last_name" : "test",
          "email" : "test@test.com",

        },
        "id" : 904,
        "scale" : 7,
        "created_at" : "2018-02-24 06:45:33",
      },
]

【问题讨论】:

  • 这是你的完整 json 内容?
  • @ReinierMelian 感谢您的评论。有连接。我更新了问题
  • 如果整个响应都存储在response中,那么你就不能像那样访问id,因为response是一个数组。
  • 您的响应中有一个对象数组,因此,您需要知道要访问哪个对象,然后才能访问 id,例如使用 for objc in response { debugPrint(objc["id"]) }should print你所有的身份证
  • @hardikparmar 谢谢.. 访问每个 [] 的 id 的最佳方法是什么?

标签: ios json swifty-json


【解决方案1】:

我假设你想从这个 JSON 数组中提取 id。您可以使用

response.map({ $0["id"]})

这将为您提供另一个仅包含 id 的数组

【讨论】:

    【解决方案2】:

    从响应数组中访问任何对象的 id 的最佳方法是:

    let id = response[index]["id"]
    // Here index is the index of the object you want to access.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-22
      • 1970-01-01
      相关资源
      最近更新 更多