首页 > 解决方案 > 如何从 JSON 对象数组中删除具有特定键/值对的所有 JSON 对象?

问题描述

我想过滤这样的数据集:

例如这里有一些假数据集:

[
    {
      "name": "Sakura",
      "hasChildren": false,
      "livesInCity": true,
      "pets": [
          { 
              "cats": ["Luna", "Milk"],
              "type": "tabby"
          }
       ]
    },
    {
      "name": "Linn",
      "hasChildren": false,
      "livesInCity": true,
      "pets": [
          { 
              "cats": ["Luna"],
              "type": "tabby"
          }
       ]
    },
    {
      "name": "Donna",
      "hasChildren": false,
      "livesInCity": false,
      "pets": [
          { 
              "cats": ["Luna", "Milk"],
              "type": "tabby"
          }
       ]
    },
    {
      "name": "Tia",
      "hasChildren": false,
      "livesInCity": false,
      "pets": [
          { 
              "cats": ["Luna", "Milk"],
              "type": "tuxedo"
          }
       ]
    },
    {
      "name": "Dora",
      "hasChildren": false,
      "livesInCity": true,
      "pets": [
          { 
              "cats": ["Artemis", "Milk"],
              "type": "tuxedo"
          }
       ]
    }
]

我想过滤掉所有有"livesInCity": false

[
    {
      "name": "Sakura",
      "hasChildren": false,
      "livesInCity": true,
      "pets": [
          { 
              "cats": ["Luna", "Milk"],
              "type": "tabby"
          }
       ]
    },
    {
      "name": "Linn",
      "hasChildren": false,
      "livesInCity": true,
      "pets": [
          { 
              "cats": ["Luna"],
              "type": "tabby"
          }
       ]
    },
    {
      "name": "Dora",
      "hasChildren": false,
      "livesInCity": true,
      "pets": [
          { 
              "cats": ["Artemis", "Milk"],
              "type": "tuxedo"
          }
       ]
    }
]

我怎样才能做到这一点?这可能吗?

在 python 中,我相信它是这样的,但我不知道如何开始使用 Swift:

people = [person for person in people if person.livesInCity == True]

另外,我如何过滤上面的数据集使其看起来像这样 - 我想按名称类型进行分类。

{
    "tabby": ["Sakura", "Linn"],
    "tuxedo": ["Dora"],
}

任何帮助将不胜感激!

标签: arraysjsonswift

解决方案


正如评论中已经提到的,您不能直接在 Swift 中处理 JSON 对象。他们需要先转换。

您可以将 JSON 解析为 Swift 对象,然后执行过滤、分组等。

struct Person: Codable {
    let name: String
    let hasChildren: Bool
    let livesInCity: Bool
    let pets: [Pet]
}

struct Pet: Codable {
    let cats: [String]
    let type: String
}
let jsonStr = "[{"name": "Sakura", ..." // your JSON string
let jsonData = jsonStr.data(using: .utf8)!
let parsedObjects = try! JSONDecoder().decode([Person].self, from: data)

然后你可以过滤你的 parsedObjects:

let filteredObjects = parsedObjects.filter({ person in person.livesInCity == true })

或更短的(swiftier)版本:

let filteredObjects = parsedObjects.filter { $0.livesInCity }

您也可以尝试按宠物类型分组:

var groupedDict = [String:[String]]()
filteredObjects.forEach{ person in
    person.pets.forEach { pet in
        if let _ = groupedDict[pet.type] {
            groupedDict[pet.type]!.append(person.name)
        } else {
            groupedDict[pet.type] = [person.name]
        }
    }
}
print(groupedDict)
//prints ["tabby": ["Sakura", "Linn"], "tuxedo": ["Dora"]]

如果您想在任何时候将对象转换回 JSON,您可以使用:

let dictData = try! JSONEncoder().encode(groupedDict)
let dictStr = String(data: dictData, encoding: .utf8)!
print(dictStr)
//prints {"tabby":["Sakura","Linn"],"tuxedo":["Dora"]}

笔记

为了简单起见,我在解码/编码对象时使用了强制可选展开( )。!您可能想改用 do-try-catch(捕获错误)。


推荐阅读