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

Output group of json objects on new lines instead of single line

目前,我的 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"}}

我想重新格式化 'block' 数据,以便打印每个 'group' 数据都在线。数据不需要保持 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)

添加换行符的推荐方法是什么?

您可以使用 Python PrettyPrint as explained in this 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"}

如果它对您不起作用或者这不是您要找的,请告诉我。 干杯!