SwiftyJSON打印字典数组中的所有值

时间:2017-10-29 21:21:11

标签: ios arrays swift swifty-json

我有一个字典数组:

dictArray

我添加了一些词典并将let json = JSON(dictArray) 转换为JSON:

for (index,subJson):(String, JSON) in json {
    print(index)
}

然后我在尝试使用此循环以JSON格式实际打印这些值时遇到了麻烦:

 {
"dictArray": [
  {
  "a": "a stuff 1",
  "b": "b stuff 1",
  "c": "c stuff 1",
  "d": "d stuff 1"
},
{
  "a": "a stuff 2",
  "b": "b stuff 2",
  "c": "c stuff 2",
  "d": "d stuff 2"
},
{
  "a": "a stuff 3",
  "b": "b stuff 3",
  "c": "c stuff 3",
  "d": "d stuff 3"
    }
  ]
}

以上循环取自SwiftyJSON文档,但它似乎并不适合我。我希望输出看起来像这样:

Counter

非常感谢所有帮助。

3 个答案:

答案 0 :(得分:0)

您不需要迭代字典来打印它。您只需使用print(json)

打印即可

如果你想循环字典,你应该使用这样的东西:

for dictionaries in json {
    for (key, value) in dictionaries {
        print("\(key): \(value)")
    }
}

答案 1 :(得分:0)

你可以像这样使用:

var array = [String:[[String:String]]]()

var dictArray = [[String:String]]()

var stuffArray1 = [String: String]()
stuffArray1["a"] = "a stuff 1"
stuffArray1["b"] = "b stuff 1"
stuffArray1["c"] = "c stuff 1"
stuffArray1["d"] = "d stuff 1"
dictArray.append(stuffArray1)

var stuffArray2 = [String: String]()
stuffArray2["a"] = "a stuff 2"
stuffArray2["b"] = "b stuff 2"
stuffArray2["c"] = "c stuff 2"
stuffArray2["d"] = "d stuff 2"
dictArray.append(stuffArray2)

var stuffArray3 = [String: String]()
stuffArray3["a"] = "a stuff 3"
stuffArray3["b"] = "b stuff 3"
stuffArray3["c"] = "c stuff 3"
stuffArray3["d"] = "d stuff 3"
dictArray.append(stuffArray3)

array["dictArray"] = dictArray

let json = JSON(array)
print(json)

答案 2 :(得分:0)

尝试一下:

for (_, object) in json ?? [] {
  let dict = NSMutableDictionary()
  for(key, value) in object {
      dict.setValue(value.stringValue, forKey: key)
     // all the values must be *String*, otherwise this fails.
  }

  print(dict)
}