简体   繁体   中英

Read and write a valid Json file output in Python

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:

  1. Read a Json File
  2. Execute a modification
  3. print the data
  4. Output a new valid Json file as "output.json"

A few problem I encourted:

  1. The Json's tuples are out of order
  2. The data is printed with an 'u' before each header
  3. The new file contains the same 'u' (Main problem)

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:

  1. You cannot read a JSON file in expected order.
  2. According to point 1, it does not make sens to write a JSON string in a specific order (since you won't be able to read it in the same order)

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 :

How to preserve ordering of items in a python dictionary?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM