Python ကို Python မှ JSON သို့ပြောင်းပါ။
Python မှ JSON သို့ပြောင်းပါ။
json.dumps()
သင့်တွင် Python အရာဝတ္ထုတစ်ခုရှိပါက၊ နည်းလမ်းကို အသုံးပြု၍ ၎င်းကို JSON စာကြောင်းအဖြစ်သို့ ပြောင်းလဲနိုင်သည် ။
ဥပမာ
Python မှ 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)
အောက်ပါအမျိုးအစားများ၏ Python အရာဝတ္ထုများကို JSON ကြိုးများအဖြစ်သို့ ပြောင်းလဲနိုင်သည်-
- အမိန့်
- စာရင်း
- tuple
- ကြိုးတစ်ချောင်း
- int
- မျှော
- မှန်ပါတယ်။
- မှားသော
- တစ်ခုမှ
ဥပမာ
Python အရာဝတ္ထုများကို JSON ကြိုးများအဖြစ်သို့ ပြောင်းပြီး တန်ဖိုးများကို ပရင့်ထုတ်ပါ-
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 မှ JSON သို့ပြောင်းသောအခါ၊ Python အရာဝတ္ထုများကို JSON (JavaScript) နှင့်ညီမျှသောအဖြစ်သို့ ပြောင်းလဲသွားသည်-
Python | JSON |
---|---|
dict | Object |
list | Array |
tuple | Array |
str | String |
int | Number |
float | Number |
True | true |
False | false |
None | null |
ဥပမာ
တရားဝင်ဒေတာအမျိုးအစားအားလုံးပါဝင်သော Python အရာဝတ္ထုကို ပြောင်းပါ-
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))