【问题标题】:function to read json data from file and convert t into a list [duplicate]从文件中读取json数据并将t转换为列表的函数[重复]
【发布时间】:2021-07-27 12:31:12
【问题描述】:

我可以编写什么代码来从我保存的 json 文件中读取 python 数据,然后将其转换为列表?

这里是一些示例代码:

def read_json_file(filename):
    """
    reads from a json file and saves the result in a list named data
    """
    with open(filename, 'r') as fp:
        
        
    # INSERT THE MISSING PIECE OF CODE HERE
    
       
        data = json.loads(content)
    return data    

【问题讨论】:

标签: python json


【解决方案1】:

要导入 json 文件,我建议使用 json 库。 在您的示例中,您首先需要导入它。

import json

然后就可以使用了

with open('filename.json', 'r') as fp:
    data = json.load(fp)

获取数据。请注意,负载与“负载”(https://docs.python.org/2/library/json.html) 不同。您只需将“内容”更改为“fp”,因为这是您引用文件的方式。

请注意,此代码存储将 json 作为 dict 返回,而不是作为列表,这与您所询问的不同,但可能您想使用什么而不知道您正在尝试做什么。

【讨论】:

    【解决方案2】:

    您基本上可以使用内置的json 模块。完整文档在这里:https://docs.python.org/3/library/json.html

    要从对象(列表、字典等任何数据)中获取 json 字符串,请使用:

        import json
    
        json_str = json.dumps(my_data)  # Get json string representation of my_data
        fp.write(json_str)              # Write json_str string to file fp
    

    一旦你写了你的文件,你就可以从文件中读取 json 字符串:

        json_str = fp.read()
    

    最后转向python对象:

        import json
    
        my_data = json.loads(json_str)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-15
      • 2019-11-23
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多