You can use json.dump() method:
with open("text", "w") as outfile:
json.dump({'numbers':n, 'strings':s, 'x':x, 'y':y}, outfile, indent=4)
Answer from alecxe on Stack OverflowYou can use json.dump() method:
with open("text", "w") as outfile:
json.dump({'numbers':n, 'strings':s, 'x':x, 'y':y}, outfile, indent=4)
Change:
dumps({'numbers':n, 'strings':s, 'x':x, 'y':y}, file, indent=4)
To:
file.write(dumps({'numbers':n, 'strings':s, 'x':x, 'y':y}, file, indent=4))
Also:
- don't need to do
file.close(). If you usewith open..., then the handler is always closed properly. result = load(file)should beresult = file.read()
Videos
You should use the optional argument indent.
header, output = client.request(twitterRequest, method="GET", body=None,
headers=None, force_auth_header=True)
# now write output to a file
with open("twitterData.json", "w") as twitterDataFile:
# magic happens here to make it pretty-printed
twitterDataFile.write(
simplejson.dumps(simplejson.loads(output), indent=4, sort_keys=True)
)
You can parse the JSON, then output it again with indents like this:
import json
mydata = json.loads(output)
print json.dumps(mydata, indent=4)
See http://docs.python.org/library/json.html for more info.
Use the indent= parameter of json.dump() or json.dumps() to specify how many spaces to indent by:
>>> import json
>>> your_json = '["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> parsed = json.loads(your_json)
>>> print(json.dumps(parsed, indent=4))
[
"foo",
{
"bar": [
"baz",
null,
1.0,
2
]
}
]
To parse a file, use json.load():
with open('filename.txt', 'r') as handle:
parsed = json.load(handle)
You can do this on the command line:
python3 -m json.tool some.json
(as already mentioned in the commentaries to the question, thanks to @Kai Petzke for the python3 suggestion).
Actually python is not my favourite tool as far as json processing on the command line is concerned. For simple pretty printing is ok, but if you want to manipulate the json it can become overcomplicated. You'd soon need to write a separate script-file, you could end up with maps whose keys are u"some-key" (python unicode), which makes selecting fields more difficult and doesn't really go in the direction of pretty-printing.
You can also use jq:
jq . some.json
and you get colors as a bonus (and way easier extendability).
Addendum: There is some confusion in the comments about using jq to process large JSON files on the one hand, and having a very large jq program on the other. For pretty-printing a file consisting of a single large JSON entity, the practical limitation is RAM. For pretty-printing a 2GB file consisting of a single array of real-world data, the "maximum resident set size" required for pretty-printing was 5GB (whether using jq 1.5 or 1.6). Note also that jq can be used from within python after pip install jq.
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