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))
...
Error:
Traceback (most recent call last):
File "<stdin>", line 5, in <module>
TypeError: 'bytes' object is not callable
>>>
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)
Output:
{
"id": 1,
"interest": [
"photo",
"tt"
],
"t": 1571751206.159
}
{
"id": 2,
"interest": [
"photo",
"tt"
],
"t": 1571751206.159
}
{
"id": 3,
"interest": [
"photo",
"tt"
],
"t": 1571751206.159
}
{
"id": 4,
"interest": [
"photo",
"tt"
],
"t": 1571751206.159
}
{
"id": 5,
"interest": [
"photo",
"tt"
],
"t": 1571751206.159
}
{
"id": 6,
"interest": [
"photo",
"tt"
],
"t": 1571751206.159
}
{
"id": 7,
"interest": [
"photo",
"tt"
],
"t": 1571751206.16
}
{
"id": 8,
"interest": [
"photo",
"tt"
],
"t": 1571751206.16
}
{
"id": 9,
"interest": [
"photo",
"tt"
],
"t": 1571751206.16
}
Note that this prints 9 separate JSON strings, not single JSON string
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.
(Oct-22-2019, 01:38 PM)dataplumber Wrote: [ -> ]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 ?
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 it
Again, 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
Thanks for the explanation.
PS : I will keep in mind to keep the code and error in separate tags