Skip to main content
 首页 » 编程设计

python之如何解析只有数字的 JSON

2024年11月24日9bonelee

我还在学习 python,我正在尝试解析来自 JSON 的数据,看起来像

{"297050": [[12, 137], [193, 776]], "297056": [[12, 203]] 

但我找不到阅读它的方法,就像我喜欢的那样

For entry 297050 this is the list [12, 137], [193, 776] For entry 297056 this is the list [12, 203]

我试过类似的东西

import json 
from pprint import pprint 
 
input_file = open ('file_JSON.txt') 
json_array = json.load(input_file) 
store_list = [] 
 
 
for obj in json_array : 
    print obj,json_array[obj] 

这给了我每个对象的对象和数组

297050 [[12, 137], [193, 776]]

但我实际上希望能够打印出现在内部的每个元素,例如 json_array[obj][0]...等

请您参考如下方法:

您可能应该使用嵌套的 for 循环..您应该打印什么取决于您期望输出的外观..但您可以试试这个:

#!/usr/bin/env python3 
import json 
 
data = '{"297050": [[12, 137], [193, 776]], "297056": [[12, 203]]}' 
 
data = json.loads(data) 
 
for k, v in data.items(): 
    print(k) 
    for list_of_ints in v: 
        for integer in list_of_ints: 
            print(integer) 

结果:

297050 
12 
137 
193 
776 
297056 
12 
203 

解释:

我们加载示例 json,并使用 items 迭代它的键值对。现在我们的键在 k 中,最外层的列表在 v 中。 v 是一个列表,一个列表的列表..所以我们将其迭代为 list_of_ints。最后我们遍历每个列表,边走边打印出最里面的整数。

如果你想要的输出是这样的:

对于条目 297050,这是列表 [12, 137],[193, 776] 对于条目 297056,这是列表 [12, 203]

然后我们可以稍微修改脚本..并摆脱很多循环。

#!/usr/bin/env python3 
import json 
 
output = "For entry {} this is the list {}" 
data = '{"297050": [[12, 137], [193, 776]], "297056": [[12, 203]]}' 
 
data = json.loads(data) 
 
for k, v in data.items(): 
    lists_with_commas = ", ".join([str(x) for x in v]) 
    print(output.format(k, lists_with_commas), end=" ") 

输出

For entry 297050 this is the list [12, 137], [193, 776] For entry 297056 this is the list [12, 203] 

解释:

我们使用一个模板字符串..它有 {} 我们想放东西的地方,所以我们可以稍后在上面运行 .format。

我们只需要键和最里面的列表。所以我们只需要一个 for 循环。我们确保通过使用 .join 获取示例中的逗号,并在其中进行列表推导,将所有列表转换为 v 中的字符串。