Python readings – Library – Json

#!/usr/bin/python
import json 

fruit = dict(apple=1, berry=3, cherry=10, date=12, elderberry=22)

days = ("Montag", "Dienstag","Mittwoch","Donnerstag",
 "Freitag", "Samstag","Sonntag")

mix = [ fruit, days ]

with open("output.json","w") as fhandle:
 json.dump(mix, fhandle)

with open("output.json","rb") as fhandle:
 newmix = json.load(fhandle)

newfruits, newdays = newmix

print type(mix), type(newmix)
print type(days), type(newdays)
print type(fruit), type(newfruits)

print newdays
print newfruits
<type 'list'> <type 'list'>
<type 'tuple'> <type 'tuple'>
<type 'dict'> <type 'dict'>
('Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag')
{'date': 12, 'cherry': 10, 'berry': 3, 'elderberry': 22, 'apple': 1}
[{"date": 12, "cherry": 10, "berry": 3, "elderberry": 22, "apple": 1},
["Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag"]]
I found a command json_pp which seems to pretty print the json.
$json_pp < output.json
[
 {
 "cherry" : 10,
 "apple" : 1,
 "date" : 12,
 "elderberry" : 22,
 "berry" : 3
 },
 [
 "Montag",
 "Dienstag",
 "Mittwoch",
 "Donnerstag",
 "Freitag",
 "Samstag",
 "Sonntag"
 ]
]

Leave a Reply

Your email address will not be published. Required fields are marked *