import json
import os
import shutil
import time
# import objectpath
import sys
import datetime
true = "true"
false = "false"
null = "null"
from datetime import datetime, timedelta
with open('./notificationsManagement/notifications.json') as json_file:
data = json.load(json_file)
day_start = 30
for tuple in data:
tuple['creationTime'] -= int(timedelta(days = day_start).total_seconds())
day_start -= 2
print(data)
text_file = open("output.json", "w")
text_file.write(str(data))
text_file.close()
I wrote a script in order to:
A few problem I encourted:
Any suggestions?
About u'foo'
:
It's normal Python behavior, u'something'
means your string is a Unicode string. see more about Unicode strings here
You can fix it simply by using this line to write your dict
as JSON string, btw you should always use json.dump()
(or json.dumps()
) to write JSON string:
text_file.write(json.dump(data))
About keys order :
First, JSON's RFC is explicit about this:
An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.
Here, " object " means " hash ", that's what we call " dictionnaries " with Python. That means keys of a JSON string are never ordered.
Moreover,
data = json.load(json_file)
loads a JSON string and parse it to a Python dictionnary. Python dicts aren't ordered neither (at least before Python3.7).
This means two things:
Regarding problem 2 & 3.
You should print it out without the Unicode output.
Reference here on writing JSON File.
How do I write JSON data to a file?
Regarding problem 3.:
If you would like ordering to be preserver you should use OrderedDict
:
Are you sure that this is actually running ? (clean all .pyc)
Data is a dictonary and you iterate over the keys (strings) and treat them like a dict
for tuple in data:
tuple['creationTime'] -= int(timedelta(days = day_start).total_seconds())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.