Retrieving JSON objects from a text file (using Python)

后端 未结 9 1606
失恋的感觉
失恋的感觉 2020-11-30 04:50

I have thousands of text files containing multiple JSON objects, but unfortunately there is no delimiter between the objects. Objects are stored as dictionaries and some of

9条回答
  •  盖世英雄少女心
    2020-11-30 05:46

    Sebastian Blask has the right idea, but there's no reason to use regexes for such a simple change.

    objs = json.loads("[%s]"%(open('your_file.name').read().replace('}{', '},{')))
    

    Or, more legibly

    raw_objs_string = open('your_file.name').read() #read in raw data
    raw_objs_string = raw_objs_string.replace('}{', '},{') #insert a comma between each object
    objs_string = '[%s]'%(raw_objs_string) #wrap in a list, to make valid json
    objs = json.loads(objs_string) #parse json
    

提交回复
热议问题