JSON
- syntax for storing and exchanging data
- text, JavaScript object notation
import json
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
# the result is a Python dictionary:
print(y["age"])
Parse JSON - Convert from JSON to Python: json.loads()
Convert from Python to JSON: json.dumps()
import json
# a Python object (dict):
x = {
"name": "John",
"age": 30,
"city": "New York"
}
# convert into JSON:
y = json.dumps(x)
convert Python objects into JSON strings:
- dict
- list
- tuple
- string
- int
- float
- True
- False
- None
import json
print(json.dumps({"name": "John", "age": 30}))
print(json.dumps(["apple", "bananas"]))
print(json.dumps(("apple", "bananas")))
print(json.dumps("hello"))
print(json.dumps(42))
print(json.dumps(31.76))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))
Python objects vs. JSON (JavaScript)
| Python |
JSON |
| dict |
Object |
| list |
Array |
| tuple |
Array |
| str |
String |
| int |
Number |
| float |
Number |
| TRUE |
TRUE |
| FALSE |
FALSE |
| None |
null |
Format the Result
- indent
- seperator
- sort key
json.dumps(x, indent=4, separators=(". ", " = "), sort_keys=True)