unable to indent json data - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: unable to indent json data (/thread-21957.html) |
unable to indent json data - dataplumber - Oct-22-2019 I am trying to print the JSON with proper indentation and sorted keys, but it throws an error. Need help to fix this Complete code : >>> import json >>> import time >>> for n in range(1, 10): ... data = {'id': n, 't': float("%.3f" % time.time()), 'interest':['photo','tt']} ... jsonData=json.dumps(data) ... data = jsonData.encode('utf-8') ... print(data (indent=4, sort_keys=True))...
RE: unable to indent json data - buran - Oct-22-2019 import json import time for n in range(1, 10): data = {'id': n, 't': float("%.3f" % time.time()), 'interest':['photo','tt']} json_data=json.dumps(data, indent=4, sort_keys=True) print(json_data) Note that this prints 9 separate JSON strings, not single JSON string
RE: unable to indent json data - dataplumber - Oct-22-2019 Thanks a lot for your reply. Can you please let me know what was wrong in my approach ? I was also doing the same thing but in single line. Isn't that allowed ? Thanks in Advance. RE: unable to indent json data - buran - Oct-22-2019 (Oct-22-2019, 01:38 PM)dataplumber Wrote: Can you please let me know what was wrong in my approach ?No, you were not doing the same thing in a single line indent and sort_keys are arguments that you can pass to json.dumps() In your snippet data is a bytes object and by using data() you were trying to call the object like a function (not possible) and getting the error and passing these arguments to itAgain, note that this is not single JSON string. in the loop you print 9 separate JSON strings. I guess you may want it to be JSON array of JSON objects RE: unable to indent json data - dataplumber - Oct-22-2019 Thanks for the explanation. PS : I will keep in mind to keep the code and error in separate tags |