SwiftyJSON 打印字典数组中的所有值
Posted
技术标签:
【中文标题】SwiftyJSON 打印字典数组中的所有值【英文标题】:SwiftyJSON print all values in an array of dictionaries 【发布时间】:2017-10-29 21:21:11 【问题描述】:我有一个字典数组:
var dictArray = [[String:String]]()
我附加了一些字典并将dictArray
转换为 JSON:
let json = JSON(dictArray)
然后我在尝试使用此循环以 JSON 格式实际打印这些值时遇到了麻烦:
for (index,subJson):(String, JSON) in json
print(index)
上面的循环取自 SwiftyJSON 文档,但它似乎对我不起作用。我希望输出看起来像这样:
"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"
]
非常感谢所有帮助。
【问题讨论】:
【参考方案1】:您不需要迭代字典来打印它。你可以简单地用print(json)
打印它
如果你想循环字典,你应该使用这样的东西:
for dictionaries in json
for (key, value) in dictionaries
print("\(key): \(value)")
【讨论】:
这段代码给了我以下错误:Error: type 'JSONGenerator.Element' (aka '(String, JSON)') does not conform to protocol 'Sequence'
和 type 'JSONGenerator.Element' (aka '(String, JSON)') does not conform to protocol 'Sequence'
【参考方案2】:
你可以这样使用:
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)
【讨论】:
【参考方案3】:试试这个:
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)
【讨论】:
以上是关于SwiftyJSON 打印字典数组中的所有值的主要内容,如果未能解决你的问题,请参考以下文章
如何比较字典值中的多个数组,并将每个数组元素的字典键映射到新数组/列表中
Swift - 使用 swiftyJSON 根据字典中的值查找字典数组的索引