Swift-查找重复的Json数据并合并

时间:2018-07-24 14:27:41

标签: arrays json swift swift3

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

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

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"]
}}

1 个答案:

答案 0 :(得分:0)

我要遍历所有字典,并从每个水果名称和数量中提取出来,然后在结果字典中重新输入或添加到已经计算的先前数量中。

enum CodingKeys

使FruitStruct符合Codable协议,可允许encoder.encode接受我们的FruitStruct数组。该结构模仿了我们想要的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 } 来将结构从结构更改为实际的JSON。

Option Explicit

Private Sub btnConnect_Click()
  Dim dataConection As New ADODB.Connection
  Dim mrs As New ADODB.Recordset
  Dim SQL As String
  Dim DBPath As String
  Dim connectionString As String

  DBPath = ThisWorkbook.FullName 'Refering the sameworkbook as Data Source

  'You can provide the full path of your external file as shown below
  connectionString = "Provider=MSDASQL.1;DSN=Excel Files;DBQ=" & DBPath & ";HDR=Yes';"

  'Open connection
  dataConection.Open connectionString

  'Create SQL query
  SQL = "SELECT * From [DataSheet$]"

  'Open record set (query or table, connection)
  mrs.Open SQL, dataConection

  Do While Not mrs.EOF
    Debug.Print "  " & mrs!Name
    mrs.MoveNext
  Loop

  mrs.Close

  'Close Connection
  dataConection.Close
End Sub