简体   繁体   中英

python extracting multiple json file from a single file in pretty format

I have multiple json files clubbed together inside a single log file(huge). Some of the json have got pretty formatting, but most have not. What is the best way in python to redirect the json to another file with pretty formatting.(Each json file ends with 3 '}' with sometimes newlines and spaces in between). Eg:- { "Sports":{"cricket":{"batsman": "Bradman","bowler":"Warne"}}}

没有用它自己,但我会尝试一包像这一个

First you should load the file with json.load , then use the indent option is json.dump .

import json
initial = json.load('yourfile.json')
json.dump(initial, 'yourfile.json', indent = 4)

you can also use the sort_keys option, which sorts the keys for the json file.

json.dump(initial, 'yourfile.json', sort_keys = True, indent = 4)

If you have multiple valid json files in one big file, you can do this:

with open('yourfile.json') as fp:
    file = fp.read()
    file = "[" + file + "]"
initial = json.loads(file)

This well work as long as there's commas sparating them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM