【问题标题】:Reading ALL objects into a list from a JSON file in Python将所有对象从 Python 中的 JSON 文件读入列表
【发布时间】:2016-03-24 23:51:02
【问题描述】:

我可能在这里做错了很多事情。 python 和 JSON 非常新。 我有多个“歌曲”-JSON 对象。我需要从文件中写入和读取。 JSON 文件看起来像这样(基本上是歌曲对象的列表,不是每行一个!这里只有两个):

[{
    "emotions": [],
    "lyrics": "2222",
    "emotionID": 0,
    "artist": "22453232",
    "sentimentScore": 0,
    "subjects": [],
    "synonymKeyWords": [],
    "keyWords": []
}, {
    "emotions": [],
    "lyrics": "244422",
    "emotionID": 0,
    "artist": "2121222",
    "sentimentScore": 0,
    "subjects": [],
    "synonymKeyWords": [],
    "keyWords": []
}]

我想将歌曲对象读入一个列表,以便我可以附加另一个歌曲对象,然后将其写回。我所拥有的显然是错误的。请帮忙。

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 python-3.x


    【解决方案1】:

    我认为您在这里遇到了几个问题。首先,有效的 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 文件和代码。请检查。我收到错误消息:UnsupportedOperation: not writable 我认为它正在读取但仍无法回写。 (我需要写回同一个文件。
    【解决方案2】:
    data.append(json.loads(f))
    

    这会将您从 JSON 文件中读取的列表作为单个元素附加到列表中。所以在你的另一个追加之后,列表将有两个元素:一个歌曲列表,以及你之后添加的一个歌曲对象。

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

    data.extends(json.loads(f))
    

    由于您的列表在此之前是空的,您也可以从 JSON 加载列表,然后附加到该列表:

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

    【讨论】:

    • 嘿,谢谢。我已经编辑了上面的问题、json 文件和代码。请检查。我收到错误消息:UnsupportedOperation: not writable 我认为它正在读取但仍无法回写。 (我需要写回同一个文件。
    • open('testWrite.json') 只是以只读模式打开文件,如果你想写入它,你需要使用例如w 模式:open('testWrite.json', 'w').
    • 好的!我这样做了。现在没有错误,但 test.Write.json 文件没有变化。
    猜你喜欢
    • 2014-01-29
    • 2020-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-25
    • 1970-01-01
    • 2018-06-02
    相关资源
    最近更新 更多