如何在Swift 4中从多个字典中写入多个JSON对象

时间:2018-07-10 13:29:34

标签: json swift file-io

假设我有两个这样的字典:

let dict = ["2": "B", "1": "A", "3": "C"]
let dict2 = ["K": "V","N": "1","A": "12"]

我想创建一个像这样的JSON对象并将其写入文件:

{
    ["2":"B", "K":"V"],
    ["N":"1", "1":"A"],
    ["3":"C", "A":"12"]
}

我有一个这样的快速代码:

let dict = ["2": "B", "1": "A", "3": "C"]
let dict2 = ["K": "V","N": "1","A": "12"]

if let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: [JSONSerialization.WritingOptions.sortedKeys,JSONSerialization.WritingOptions.prettyPrinted]){
    try? jsonData.write(to: URL(fileURLWithPath: <filepath>), options: Data.WritingOptions.atomic)
}

但是此代码只写第一个字典的内容。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

您所需的输出是字典数组

    let dict = ["2": "B", "1": "A", "3": "C"]
    let dict2 = ["K": "V","N": "1","A": "12"] // THIS SHOULD BE ["N": "1", "K": "V", "A": "12"]


   // convert to array
    var array1 = [[String:String]]()
    dict.map{array1.append([$0.key:$0.value])}

    var array2 = [[String:String]]()
    dict2.map{array2.append([$0.key:$0.value])}

    print(array1)
    print(array2)
    // Merge both array's dictionary 
    var finalArray = [[String:String]]()
    for i in 0..<array1.count {
        var dict = array1[i]
        dict.merge(array2[i]) {$1}
        finalArray.append(dict)
    }
    print(finalArray)

最终输出

  

数组1 [[“”“:” B“],[” 1“:” A“],[” 3“:” C“]]

     

数组2 [[“”“:” 1“],[” K“:” V“],[” A“:” 12“]]

     

合并

     

[[[“ N”:“ 1”,“ 2”:“ B”],

     

[“ 1”:“ A”,“ K”:“ V”],

     

[“ A”:“ 12”,“ 3”:“ C”]             ]

还要注意您提供的dict2。请记住,字典没有任何排序顺序。所以

["K": "V","N": "1","A": "12"]将按["N": "1", "K": "V", "A": "12"]的顺序处理