JSON¶
JSON adalah sintaksis untuk menyimpan dan bertukar data.
JSON adalah teks yang ditulis dengan notasi objek JavaScript.
JSON in Python¶
Python memiliki paket bawaan yang disebut ``, yang dapat digunakan untuk bekerja dengan data JSON.
import json
Parse JSON - Convert from JSON to Python¶
Jika Anda memiliki string JSON, Anda dapat menguraikannya dengan menggunakan metode json.loads().
Catatan
The result will be a Python dictionary.
# Convert from JSON to Python:
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"])
Convert from Python to JSON¶
Jika Anda memiliki objek Python, Anda dapat mengubahnya menjadi string JSON dengan menggunakan metode json.dumps().
# Convert from Python to JSON:
import json
# a Python object (dict):
x = {
"name": "John",
"age": 30,
"city": "New York"
}
# convert into JSON:
y = json.dumps(x)
# the result is a JSON string:
print(y)
Anda dapat mengonversi objek Python jenis berikut menjadi string JSON:
dict
list
tuple
string
int
float
True
False
None
# Convert Python objects into JSON strings, and print the values:
import json
print(json.dumps({"name": "John", "age": 30})) # {"name": "John", "age": 30} print(json.dumps(["apple", "bananas"])) # ["apple", "bananas"] print(json.dumps(("apple", "bananas"))) # ["apple", "bananas"] print(json.dumps("hello")) # "hello" print(json.dumps(42)) # 42 print(json.dumps(31.76)) # 31.76 print(json.dumps(True)) # true print(json.dumps(False)) # false print(json.dumps(None)) # null
Saat Anda mengonversi dari Python ke JSON, objek Python dikonversi menjadi padanan JSON (JavaScript):
Python |
JSON |
|---|---|
dict |
Object |
list |
Array |
tuple |
Array |
str |
String |
int |
Number |
float |
Number |
True |
true |
False |
false |
None |
null |
# Convert a Python object containing all the legal data types:
import json
- x = {
"name": "John", "age": 30, "married": True, "divorced": False, "children": ("Ann","Billy"), "pets": None, "cars": [
{"model": "BMW 230", "mpg": 27.5}, {"model": "Ford Edge", "mpg": 24.1}
]
}
print(json.dumps(x)) # {"name": "John", "age": 30, "married": true, "divorced": false, "children": ["Ann","Billy"], "pets": null, "cars": [{"model": "BMW 230", "mpg": 27.5}, {"model": "Ford Edge", "mpg": 24.1}]}
Format the Result¶
Contoh di atas mencetak string JSON, tetapi tidak mudah dibaca, tanpa indentasi dan jeda baris.
Metode json.dumps() memiliki parameter untuk memudahkan pembacaan hasilnya:
#Use the indent parameter to define the numbers of indents:
json.dumps(x, indent=4)
########
{
"name": "John",
"age": 30,
"married": true,
"divorced": false,
"children": [
"Ann",
"Billy"
],
"pets": null,
"cars": [
{
"model": "BMW 230",
"mpg": 27.5
},
{
"model": "Ford Edge",
"mpg": 24.1
}
]
}
Anda juga dapat menentukan pemisah, nilai defaultnya adalah (", ", ": "), yang berarti menggunakan koma dan spasi untuk memisahkan setiap objek, dan titik dua dan spasi untuk memisahkan kunci dari nilai:
# Use the separators parameter to change the default separator:
json.dumps(x, indent=4, separators=(". ", " = "))
Order the Result¶
Metode json.dumps() memiliki parameter untuk mengurutkan kunci dalam hasil:
Gunakan parameter sort_keys untuk menentukan apakah hasilnya harus diurutkan atau tidak:
json.dumps(x, indent=4, sort_keys=True)