【问题标题】:How to loop through json file如何循环遍历json文件
【发布时间】:2020-06-12 05:48:20
【问题描述】:

我不知道如何使用 forloop 迭代这些 json 文件,我尝试了它打印所有内容,但我只需要打印 id 和类。

for (k, v) in bin3.items():  
if k == 'ID':
    print(v)

上面的代码没有打印任何东西。

这是我的 json 文件内容 { "content": { "ID": "stringIdentity:@5", "class": 1, "annotations": [ { "ID": 1, "class": 2, "body": "" }]}}

dir_with_bin_folder=[]
for root, directories, files in os.walk(directory): 
    for filename in files:
        if filename=='@3.bin':
            with open(root+'/'+filename) as json_file:
                bin3 = json.load(json_file)
                df = pd.read_json(root+'/'+filename)
                print(filename)
                print(bin3)
                annotations=bin3['annotations']
                bin3_content=(bin3['content'])
                bin3_IID=(bin3['ID')
                bin3_class=(bin3['class'])
                for i in annotations:
                bin3_ID=(i['ID'])
                bin3_class=(i['class'])
                bin3_body=(i['body'])
                print(bin3_ID)

我在上面也试过了,但我得到了键值错误

【问题讨论】:

  • json 可以加载为 python dict。然后可以轻松访问内容。您要提取什么内容?
  • 我没有看到任何你可以在这个 JSON 中循环的东西......你需要一个迭代来循环(比如一个列表),而不是一个 JSON/字典。
  • 也许你想做this之类的事情?

标签: python json


【解决方案1】:

json 文件只能从上下文中包含的 annotations 键迭代。如果要从注释中打印 ID 和类,则需要遍历注释列表并获取键等于“ID”和“类”的值。

with open(root+'/'+filename) as json_file:
    bin3 = json.load(json_file)

for annotation in bin3['content']['annotations']:
    id_value = annotation.get('ID',None)
    class_value = annotation.get('class',None)
    print(id_value, class_value, sep=' ')

【讨论】:

  • 我怀疑我是否在“注释”中还有一个列表 ['transformations'] 我如何从中获取详细信息?此注释和转换是内容中的关键。那么我该如何给出这个 foreg:bin3 ['content']['annotations']['transformations'] 或嵌套 for 循环?
  • 然后您也可以在当前注释循环中循环遍历该标记。对于注解中的转换['transformations']:
  • 我得到了 keyerror:我刚刚尝试过的转换就像 bin3 中的注释 ['content']['annotations']: print(annotation) 用于注释中的转换 ['transformations']: print(transformation )
  • 好吧,假设你的 json 现在看起来像这样: bin3 = {"content": { "ID": "stringIdentity:@5", "class": 1, "annotations": [ { “ID”:1,“类”:2,“主体”:“”,“转换”:[ { “ID”:1,“类”:2,“主体”:“”}] }]}}
  • 那么这应该可以工作:对于 bin3['content']['annotations'] 中的注释: id_value = annotation.get('ID',None) class_value = annotation.get('class', None) 用于 annotation.get('transformations',None) 中的转换: trans_id_value = transformation.get('ID', None) trans_class_value = transformation.get('class', None)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-18
  • 2021-04-26
相关资源
最近更新 更多