将JSON文件内容转换为Python列表

2024-06-02 05:04:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我的项目需要一个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作为可用列表


Tags: 文件项目字符串代码jsonhello列表world
2条回答

假设要将一串单词转换为列表:

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())

您可以将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

相关问题 更多 >