在新行上输出json对象组而不是单行

时间:2017-01-08 23:53:31

标签: json python-3.x pretty-print

目前,我的json数据格式为:

{"1": {"name": "camera", "aisle": "M.53", "status": "Out of Stock"}, "2": {"name": "camera", "aisle": "M.36", "status": "In Stock"}, "3": {"name": "camera", "aisle": "M.38", "status": "In Stock"}}

我想重新格式化'块'数据,以便打印每个组'数据在线上。数据不需要保持json格式 - 我只是想将信息分解成单独的行(类似于以下内容):

 "1": {"name": "camera", "aisle": "M.53", "status": "Out of Stock"}, 
 "2": {"name": "camera", "aisle": "M.36", "status": "In Stock"}, 
 "3": {"name": "camera", "aisle": "M.38", "status": "In Stock"}

以下是我使用的代码:

 result = json.loads(data['searchResults'])['results'][0]
        summary = {
            'name': result['name'],
            'aisle': result['price']['aisle'][0],
            'status': result['inventory']['status'],
            }
        results[store] = summary

with open('Testing.txt', 'w') as outfile:
    outfile.write('\n')
    json.dump(results, outfile)

建议的添加换行符的方法是什么?

1 个答案:

答案 0 :(得分:-1)

您可以按照PrettyPrint中的说明使用Python answer。 希望这会有所帮助:)

编辑: 道歉,我应该更清楚。 我使用了以下测试代码并获得了您想要的输出:

import json

#example json from your question as text
before_parsed = '{"1": {"name": "camera", "aisle": "M.53", "status": "Out of Stock"}, "2": {"name": "camera", "aisle": "M.36", "status": "In Stock"}, "3": {"name": "camera", "aisle": "M.38", "status": "In Stock"}}'

#parsing the text to get the results as a json object
results = json.loads(before_parsed)

#print (results)

#############copy the code from here to your program################
#sorting your json output by keys so that you get your output as {"1":{}, "2":{}...}
results_str = json.dumps(results, sort_keys=True)

#removing the outer brackets {}, now the results_str would look something like this "1":{}, "2":{}...
results_str = results_str[1:-1]

#splitting the string by "}," as delimiter, so results_list would look like this ["1":{, "2":{, "3":{}]
results_list = results_str.split("},")

#print the results to the file as per the desired format
with open('Testing.txt', 'w') as outfile:
    outfile.write('\n')
    for p in results_list[:-1]:
        print (p+'}', file=outfile)
    print (results_list[-1], file=outfile)

以下内容将打印到Testing.txt文件:

"1": {"aisle": "M.53", "name": "camera", "status": "Out of Stock"}
"2": {"aisle": "M.36", "name": "camera", "status": "In Stock"}
"3": {"aisle": "M.38", "name": "camera", "status": "In Stock"}

如果它不适合您,或者这不是您想要的,请告诉我。 干杯!