【问题标题】:Convert JSON file contents to Python list将 JSON 文件内容转换为 Python 列表
【发布时间】:2021-06-26 15:32:37
【问题描述】:

我的项目需要一个 JSON 文件来记住一串单词。代码转换一个列表:

lst = ['Hello', ' there', ' world!']

转换成 JSON 文件上的字符串。它通过使用代码来做到这一点:

lst = "".join(lst)
jsonFile = open("example.json", "w")
jsonFile.write(json.dumps(lst))
jsonFile.close()

新的example.json:

"Hello there world!"

然后如何将example.json 转换回lst 作为可用列表?

【问题讨论】:

    标签: python json string list


    【解决方案1】:

    假设你想将一串单词转换成一个列表:

    my_string = "Hello there world!"
    
    print(my_string.split()) # gives you ['Hello', 'there', 'world!']
    

    这是您正在寻找的输出吗?我怀疑额外的引号是因为您可能在将字符串拆分为列表之前再次对字符串进行了类型转换

    基于已编辑的问题:

    lst = ['"Hello there world!"'] 
    output_string = ''.join(map(str, lst)).replace('"', "")
    print(output_string.split())
    

    【讨论】:

    • my_string.split() 已经是一个列表。此外,默认情况下split 将按空格分隔。
    • 那么我需要将 JSON 文件中的字符串转换回列表。我该怎么做?
    • 我看到你已经进一步编辑了这个问题。要回答这个问题,您是否希望将所有 json 内容放入一个列表中?如果是这样,您可以阅读每一行并附加到列表中。否则,您可以为 json 中的每一行列出一个列表。可以举个例子说明一下 json 文件的样子吗?
    • 一个列表。我希望列表“lst”本质上将 example.json 作为单词列表粘贴到自身中。这有意义吗?
    • 当您说“JSON 文件”时,表示文件内容由键、值对组成。例如,{姓名:“John Doe”,年龄:“50”}。按照您的要求,您希望您的列表是lst = ["John Doe", "50"] 吗?
    【解决方案2】:

    您可以将lst 直接转储到json,无需加入:

    import json
    
    lst = ['Hello', ' there', ' world!']
    
    with open('example.json', 'w') as f:
        json.dump(lst, f)
    

    然后您可以从文件中加载列表:

    with open('example.json') as f:
      lst = json.load(f)
    

    如果您希望或需要坚持使用原始代码来保存文件,您可以像这样加载它:

    with open('example.json') as f:
      data = json.load(f)
      lst = data.split()
      #lst = [lst[0]] + [' ' + i for i in lst[1:]] #if you want to reinsert the spaces
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多