Python Tutorial
JSON | Python |
---|---|
object | dict |
array | list |
string | str |
number (int) | int |
number (real) | float |
true | True |
false | False |
null | None |
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float, int & float derived enums | number |
True | true |
False | false |
None | null |
#!/usr/bin/python import json print(json.dumps(['json1', {'json2': ('json3', None, 1.0, 2)}]))Output:
$ python test_json.py ["json1", {"json2": ["json3", null, 1.0, 2]}]
#!/usr/bin/python import json print(json.dumps("\"json1\njson2"))Output:
$ python test_json.py "\"json1\njson2"
#!/usr/bin/python import json print(json.dumps({"d": 1, "b": 2, "f": 3}, sort_keys=True))Output:
$ python test_json.py {"b": 2, "d": 1, "f": 3}
#!/usr/bin/python import json print(json.dumps([1, 2, 3, {'4': 5, '6': 7}], separators=(',', ':')));Output:
$ python test_json.py [1,2,3,{"4":5,"6":7}]
#!/usr/bin/python import json print(json.dumps({'d': 2, 'c': 3}, sort_keys=True, indent=4))Output:
$ python test_json.py { "c": 3, "d": 2 }
#!/usr/bin/python import json json_data = [1, 'json', 'list']; f = open("file_name.txt", "w"); json.dump(json_data, f); f.close(); print("serialized python object into JSON Format");Output:
$ python test_json.py serialized python object into JSON Format file_name.txt file contains below text [1, "json", "list"]
#!/usr/bin/python import json print(json.loads('["json1", {"json2":["json3", null, 1.0, 2]}]'));Output:
$ python test_json.py [u'json1', {u'json2': [u'json3', None, 1.0, 2]}]
#!/usr/bin/python import json print(json.loads('"\\"json1\\njson2"'));Output:
$ python test_json.py "json1 json2
#!/usr/bin/python import json def need_sum(dict): if '__sum__' in dict: return (dict['value1']+dict['value2']); return dict; print(json.loads('{"__sum__": true, "value1": 8, "value2": 5}', object_hook=need_sum));Output:
$ python test_json.py 13
#!/usr/bin/python import json f = open("file_name.txt", "r"); print(json.load(f)); f.close();Output:
$ python test_json.py [1, u'json', u'list']
Python Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us
| Report website issues in Github
| Facebook page
| Google+ page