Currently, my json data is formatted as:
{"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"}}
I would like to reformat the 'block' of data so that it prints each 'group' of data is on its on line. The data does not need to remain in json format - I simply want to break up the information into individual lines (similar to the following):
"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"}
Here is the code I'm using:
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)
What is a recommended way to go about adding the line breaks?
You can use Python PrettyPrint as explained in this answer. Hope this helps :)
Edit: Apologies, I should have been clearer. I used the following test code and achieved your desired output:
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)
And the following is printed to Testing.txt file:
"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"}
Let me know if it doesn't work for you or if this is not what you are looking for. Cheers!