Read and write a valid Json file output in Python

read json file python
python extract data from json file
python read json file line by line
python write json to file pretty
how to filter data from json file in python
python read json file from directory
how to read json file
python3 read json file
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)

Reading and Writing JSON to a File in Python, How do you write a JSON response to a python file? To handle the data flow in a file, the JSON library in Python uses dump() or dumps() function to convert the Python objects into their respective JSON object, so it makes easy to write data to files. See the following table given below.

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?

Reading and Writing JSON to a File in Python, The easiest way to write your data in the JSON format to a file using Python is to use store your data in a dict object, which can contain other nested dict s, arrays, booleans, or other primitive types like integers and strings. You can find a more detailed list of data types supported here. The easiest way to write your data in the JSON format to a file using Python is to use store your data in a dict object, which can contain other nested dict s, arrays, booleans, or other primitive types like integers and strings. You can find a more detailed list of data types supported here.

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())

How to Read and Write Json Files in Python – Linux Hint, If you have used JSON data from another program or obtained as a string format of JSON, then it can easily be deserialized with load() , which is usually used to  If you do not know how to read and write files in Python, we recommend you to check Python File I/O. Python Convert to JSON string You can convert a dictionary to JSON string using json.dumps() method.

Reading and Writing JSON in Python, To read the test.json file in python, you can use the code below: import json. with open ("test.json") as f: {'codename': 'Eoan Ermine', 'version': 'Ubuntu 19.10'} <class 'dict'> import json. { $ echo '{"codename": "Eoan Ermine", "version": "Ubuntu 19.10"}' | python3 -m json. { $ python3 -m json. Writing to JSON File in Python The same table will now be used to convert python data types to json equivalents. To convert a python dict to a json object we will use the method dumps from the json module. It will return a string which will be converted into json format.

Python JSON: Read, Write, Parse JSON (With Examples), JSON is a text-based format which is derived from JavaScript object serializes it and writes the output (which is a JSON string) to a file like  Writing JSON to a file To output the JSON to a file, open the file, say contacts.json for example, in write mode and use the json.dump () function to convert the dictionary person_dict to a string and save to the file contacts.json. If the file does not already exist then it will be created.

How to Read and Write to JSON File in Python, In this tutorial, you will learn to parse, read and write JSON in Python with the help of examples. Also, you will learn to convert JSON to dict and pretty print it. JSON (JavaScript Object Notation) is a popular data format used for In the above program, we have opened a file named person.txt in writing mode using 'w​' . json.load (f) is used to load the json file into python object.It takes an argument i.e., file name. Now we have to read the data from json file. For reading data we have to start a loop that will fetch the data from the list. print (emp) method simply print the data of json file.

Comments
  • The u in prefix indicates that it is a unicode. Check this link for more; stackoverflow.com/questions/2464959/…