【问题标题】:Swift - Finding duplicate Json data and mergingSwift - 查找重复的 Json 数据并合并
【发布时间】:2019-01-01 05:26:30
【问题描述】:

我正在使用 swiftyjson 来处理我的 json 数据。

目前,我正在接收具有我想要合并在一起的值的数据。 (如果您看一下下面的示例,它会更有意义。我尝试了许多不同的方法,例如使用 for 循环来遍历 JSON 数据,但这会重复所有内容。我还尝试将我的 json 更改为二维数组然后对其进行过滤,但这似乎使事情变得复杂。必须有一种更简单的方法......

var jsondata = {
{
    fruit: "APPLE"
    amount: 10
},{
    fruit: "Mango"
    amount: 5 
},{
    fruit: "APPLE"
    amount: 5 
},{
    fruit: "Mango"
    amount: 5 
},{
    fruit: "orange"
    amount: 500
}
}


var NEWjsondata = 
{
    {
    fruit: "APPLE"
    amount: 15
    },
    {
    fruit: "Mango"
    amount: 10
    },
    {
    fruit: "orange"
    amount: 500
    }
}

我的方法

var arr = ["Apple","Mango","Orange"]
for (key,json) in jsondata {
arr.append(json["fruit"])
if arr.contains(json["fruit"]){
json["amount"] = json["amount"] + json["amount"]
}}

【问题讨论】:

  • 那不是有效的 JSON 数据。 Here你可以看看它是否有效。
  • @Purpose 这是一个伪代码伙伴:]
  • 显示您尝试过的代码。创建一个可以支持数组中项目类型的新字典,然后遍历数组,如果“水果”已经存在,则添加数量,如果没有则添加水果和数量。
  • @Scriptable 用我的方法更新了帖子。您的建议的问题是它会导致添加重复的条目。这是我采取的第一种方法。
  • 如果您先检查水果是否存在,则不会。

标签: arrays json swift swift3


【解决方案1】:

我正在浏览所有字典并从每个水果名称和数量中提取,然后在结果字典中创建一个新条目或添加到之前已经计算的数量。

func mergedDict(dictionaries: [[String: Any]]) -> [String: Int] {
    guard dictionaries.count != 0 else { return [:] }

    var result = [String: Int]()

    dictionaries.forEach { dict in
        var name: String?
        var amount: Int?
        dict.forEach{ arg in
            switch arg.key {
            case "fruit":
                name = arg.value as! String
            case "amount":
                amount = arg.value as! Int
            default:
                fatalError("does not exist.")
            }
        }

        guard let fruit = name else { fatalError("name is nil.") }
        guard let newAmount = amount else { fatalError("amount is nil.") }

        guard let priorAmount = result[fruit] else {
            result[fruit] = newAmount
            return
        }
        result[fruit] = priorAmount + newAmount
    }

    return result
}

使 FruitStruct 符合 Codable 协议允许 encoder.encode 获取我们的 FruitStruct-array。该结构模仿了我们想要的 JSON。可以添加enum CodingKeys 来更改从结构到实际JSON 的映射。

struct FruitStruct: Codable {
    let fruit: String
    let amount: Int
}

func json(fromDict: [String: Int]) throws -> String {
    let fruitStructs = fromDict.map { arg in
        return FruitStruct(fruit: arg.key, amount: arg.value)
    }

    let encoder = JSONEncoder()
    encoder.outputFormatting = .prettyPrinted

    let data = try encoder.encode(fruitStructs)

    guard let string = String(data: data, encoding: .utf8) else {
        fatalError("failed to decode json-Data to String with utf8.")
    }
    return string
}

【讨论】:

  • @iloveStackOverflow 您可以创建一个struct FruitStruct { let fruit: String; let amount: Int},将mergedDict 映射到[FruitStruct] 并使用JSONEncoder 对其进行编码。你能做到还是需要更多指导?
  • 顺便说一句.. JSONEncoder 上有一个 .prettyPrint 设置。
  • 没关系,我会弄清楚的。再次感谢您:]
  • 实际上是的,我需要更多关于结构水果的指导。自己尝试过,但似乎无法正常工作。
  • @iloveStackOverflow 为此,您必须阅读 Encodable、CodingKeys 和 map 函数。您应该牢记 .filter、.map、.sorted、.enumerated、.forEach,所以也要仔细阅读它们。他们让生活变得轻松多了。 Map 使用泛型来尝试确定输出类型。更新了帖子。
猜你喜欢
  • 2022-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-09
  • 2020-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多