【问题标题】:Python fetch data from json filePython从json文件中获取数据
【发布时间】:2018-08-20 19:54:04
【问题描述】:

我是 python 新手。 我正在尝试从 data.json 文件中提取数据。

如何获得“Files_Names”和“project_name”? 另外,如何操作数据,“XX\XX\X”是多余的字符串。

希望输出:

File_Names = ih/1/2/3.java
             ihh/11/22/33.java.java
Project_name = android/hello
File_Names = hi/1/2/3.java
             hih/11/22/33.java.java
Project_name = android/helloworld

数据.json

{
    "changed": [
        {
            "prev_revision": "a09936ea19ddc9f69ed00a7929ea81234af82b95", 
            "added_commits": [
                {
                    "Lines_Deleted": 28, 
                    "File_Names": [
                        "1\t3\tih/1/2/3.java", 
                        "1\t1\tihh/11/22/33.java.java"
                    ], 
                    "Files_Modified": 8, 
                    "Lines_Inserted": 90
                }
            ], 
            "project_name": "android/hello"
        }, 
       {
            "prev_revision": "a09936ea19ddc9f69ed00a7929ea81234af82b95", 
            "added_commits": [
                {
                    "Lines_Deleted": 28, 
                    "File_Names": [
                        "14\t3\thi/1/2/3.java", 
                        "1\t1\thih/11/22/33.java.java"
                    ], 
                    "Files_Modified": 8, 
                    "Lines_Inserted": 90
                }
            ], 
            "project_name": "android/helloworld"
        }

    ]
}

【问题讨论】:

  • 我正在寻找如何处理 sub_dict 条目。

标签: python json parsing


【解决方案1】:

import json 然后使用json.load(open('data.json')) 读取文件。它将作为 Python 对象(字典、列表、整数、字符串、浮点数)的嵌套层次结构加载,您可以进行相应的解析。

这里有一些东西可以激发您的想象力并传达这个概念。

import json
x = json.load(open('data.json'))
for sub_dict in x['changed']:
    print('project_name', sub_dict['project_name'])

    for entry in sub_dict['added_commits']:
        print (entry['File_Names'])

【讨论】:

  • 我被“sub_dict”卡住了。这很有帮助。谢谢!
【解决方案2】:

你可以使用这种方法

import json

with open('data.json') as json_file: 
    data = json.loads(json_file)
    for item in data['changed']:
        print(item['project_name'], item['added_commits']['File_Names'])

【讨论】:

    【解决方案3】:

    您可以在json 模块中使用类似的东西

    import json
    f = open("file_name.json", "r")
    data = f.read()
    jsondata = json.loads(data) 
    print jsondata # all json file 
    
    print jsondata["changed"] # list after dictionary 
    
    print jsondata["changed"][0] # This will get you all you have in the first occurence within changed
     f.close()
    

    从这里您可以进一步使用 json 中的任何元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-27
      • 2022-01-23
      相关资源
      最近更新 更多