Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从Python中的JSON文件将所有对象读入列表_Json_Python 3.x - Fatal编程技术网

从Python中的JSON文件将所有对象读入列表

从Python中的JSON文件将所有对象读入列表,json,python-3.x,Json,Python 3.x,我可能在这里做了很多错事。对python和JSON非常陌生。 我有多个“song”-JSON对象。我需要从文件中写入和读取。JSON文件如下所示(基本上是歌曲对象列表,不是每行一个!这里只有两个): 我想把歌曲对象读入一个列表,这样我就可以附加另一个歌曲对象,然后再写回去。我所说的显然是错的。请帮忙 import json from song import Song def writeToFile(): lyrics = input( "enter lyrics: " ) art

我可能在这里做了很多错事。对python和JSON非常陌生。 我有多个“song”-JSON对象。我需要从文件中写入和读取。JSON文件如下所示(基本上是歌曲对象列表,不是每行一个!这里只有两个):

我想把歌曲对象读入一个列表,这样我就可以附加另一个歌曲对象,然后再写回去。我所说的显然是错的。请帮忙

import json
from song import Song
def writeToFile():
    lyrics = input( "enter lyrics: " )
    artist = input("enter artist name: ")
    songObj = Song(lyrics, artist)
    print(vars(songObj))
    data = []
    with open('testWrite.json') as file:
        data = json.load(file)
        data.append(vars(songObj))
        print(data)
    with open('testWrite.json', 'w') as file:
        json.dump(data, file) 

ctr = "y"
while (ctr=="y"):
    writeToFile()
    ctr = input("continue? y/n?")

如果每次我想添加一个新的歌曲对象时都可以避免加载所有对象,那么也可以接受其他建议

我想你这里有几个问题。首先,有效的JSON不使用单引号('),而是使用双引号(“)。您正在寻找类似以下内容:

[{
"id":123,
"emotions":[],
"lyrics":"AbC",
"emotionID":0,
"artist":"222",
"sentimentScore":0,
"subjects":[],
"synonymKeyWords":[],
"keyWords":[]
},

{
"id":123,
"emotions":[],
"lyrics":"EFG",
"emotionID":0,
"artist":"223",
"sentimentScore":0,
"subjects":[],
"synonymKeyWords":[],
"keyWords":[]
}
]
其次,您需要打开json文件进行读取,然后将其作为json加载

with open(read_file) as file:
  data = json.load(file)

with open(write_file, 'w') as file:
  json.dump(data, file)

print(data)
这会将从JSON文件中读取的列表作为单个元素附加到列表中。因此,在另一个附加之后,列表将包含两个元素:一个歌曲列表,以及随后添加的一个歌曲对象

您应该使用
list.extend
扩展另一个列表中的项目:

data.extends(json.loads(f))
由于在此之前列表为空,您也可以从JSON加载列表,然后附加到该列表:

data = json.loads(f)
data.append(vars(songObj))

嘿,谢谢。我已经编辑了上面的问题、json文件和代码。请检查。我收到错误:不支持操作:不可写我认为它正在阅读,但仍然无法写回。(我需要回写到同一个文件。嘿,谢谢。我已经编辑了上面的问题、json文件和代码。请检查。我收到错误:不支持操作:不可写我认为它正在读取,但仍然无法回写。(我需要回写到同一个文件。
open('testWrite.json'))
只需以只读模式打开文件,如果您想对其进行写入,则需要使用例如
w
模式:
open('testWrite.json','w')
。好的!我这样做了。现在没有错误,但对test.write.json文件没有更改。
data.extends(json.loads(f))
data = json.loads(f)
data.append(vars(songObj))