Retrieving JSON objects from a text file (using Python)

后端 未结 9 1609
失恋的感觉
失恋的感觉 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:24

    How about something like this:

    import re
    import json
    
    jsonstr = open('test.json').read()
    
    p = re.compile( '}\s*{' )
    jsonstr = p.sub( '}\n{', jsonstr )
    
    jsonarr = jsonstr.split( '\n' )
    
    for jsonstr in jsonarr:
       jsonobj = json.loads( jsonstr )
       print json.dumps( jsonobj )
    

提交回复
热议问题