formatting json output in Python
python - How do I write JSON data to a file? - Stack Overflow
Handling JSON files with ease in Python
How to open contents of JSON file in Python
JSON.load takes a file handle as a parameter, and JSON.loads takes the actual JSON object as a string.
with open('my_json.txt', 'r') as f:
my_json = JSON.load(f)or
json_string = '{"thing": "value"}'
my_json = JSON.loads(json_string) More on reddit.com Videos
Hi,
I would like to read json into Python code, and then output processed json. In order to get started with this, I have written very basic Python, and am attempting to read in very basic json I found online.
The input json is:
{
"firstName": "John",
"lastName": "Doe",
"hobbies": ["biking", "coding", "rapping"],
"age": 35,
"children": [
{
"firstName": "hector",
"age": 6
},
{
"firstName": "cassandra",
"age": 8
}
]
}The code is:
import json
if __name__ == '__main__':
print( "start" )
# read and load input json
json_input_filename = "input.json"
json_input = open( json_input_filename )
json_input_dict = json.load( json_input )
# write output json
json_output_filename = "output.json"
with open( json_output_filename, 'w' ) as json_output:
json.dump( json_string, json_output )
print( f"end" )and the output is:
"{\"firstName\": \"John\", \"lastName\": \"Doe\", \"hobbies\": [\"biking\", \"coding\", \"rapping\"], \"age\": 35, \"children\": [{\"firstName\": \"hector\", \"age\": 6}, {\"firstName\": \"cassandra\", \"age\": 8}]}"What can I do in order to preserve something resembling the original formatting? I'm going to load this output into some other code in order to process it further.
Thank you very much
data is a Python dictionary. It needs to be encoded as JSON before writing.
Use this for maximum compatibility (Python 2 and 3):
import json
with open('data.json', 'w') as f:
json.dump(data, f)
On a modern system (i.e. Python 3 and UTF-8 support), you can write a nicer file using:
import json
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
See json documentation.
To get utf8-encoded file as opposed to ascii-encoded in the accepted answer for Python 2 use:
import io, json
with io.open('data.txt', 'w', encoding='utf-8') as f:
f.write(json.dumps(data, ensure_ascii=False))
The code is simpler in Python 3:
import json
with open('data.txt', 'w') as f:
json.dump(data, f, ensure_ascii=False)
On Windows, the encoding='utf-8' argument to open is still necessary.
To avoid storing an encoded copy of the data in memory (result of dumps) and to output utf8-encoded bytestrings in both Python 2 and 3, use:
import json, codecs
with open('data.txt', 'wb') as f:
json.dump(data, codecs.getwriter('utf-8')(f), ensure_ascii=False)
The codecs.getwriter call is redundant in Python 3 but required for Python 2
Readability and size:
The use of ensure_ascii=False gives better readability and smaller size:
>>> json.dumps({'price': '€10'})
'{"price": "\\u20ac10"}'
>>> json.dumps({'price': '€10'}, ensure_ascii=False)
'{"price": "€10"}'
>>> len(json.dumps({'абвгд': 1}))
37
>>> len(json.dumps({'абвгд': 1}, ensure_ascii=False).encode('utf8'))
17
Further improve readability by adding flags indent=4, sort_keys=True (as suggested by dinos66) to arguments of dump or dumps. This way you'll get a nicely indented sorted structure in the json file at the cost of a slightly larger file size.