Python JSON

జెఐఎస్ డేటా నిర్వహించడానికి మరియు మార్పిడి కోసం ఉపయోగించబడుతుంది.

జెఐఎస్ జావాస్క్రిప్ట్ ఆబ్జెక్ట్ నోటేషన్ (జావాస్క్రిప్ట్ ఆబ్జెక్ట్ నోటేషన్) తో రాయబడింది.

పైథాన్ లో జెఐఎస్

పైథాన్ లో ఒక పేరుతో ఉన్నది జెఐఎస్ జెఐఎస్ డేటా నిర్వహించడానికి ఉపయోగపడుతుంది。

ఉదాహరణ

దాని బుల్లెట్ ప్యాక్ ను దిగుమతి చేయండి జెఐఎస్ మాడ్యూల్:

import json

జెఐఎస్ పరిశీలించండి - జెఐఎస్ ను పైథాన్ లో మార్చండి

జెఐఎస్ స్ట్రింగ్ ఉంటే, దానిని ఉపయోగించవచ్చు json.loads() 方法对其进行解析。

结果将是 Python 字典。

ఉదాహరణ

把 JSON 转换为 Python:

import json
# 一些 JSON:
x =  '{ "name":"Bill", "age":63, "city":"Seatle"}'
# 解析 x:
y = json.loads(x)
# 结果是 Python 字典:
print(y["age"])

ఉదాహరణను నడుపుము

把 Python 转换为 JSON

若有 Python 对象,则可以使用 json.dumps() 方法将其转换为 JSON 字符串。

ఉదాహరణ

把 Python 转换为 JSON:

import json
# Python 对象(字典):
x = {
  "name": "Bill",
  "age": 63,
  "city": "Seatle"
}
# 转换为 JSON:
y = json.dumps(x)
# 结果是 JSON 字符串:
print(y)

ఉదాహరణను నడుపుము

您可以把以下类型的 Python 对象转换为 JSON 字符串:

  • dict
  • list
  • tuple
  • string
  • int
  • float
  • True
  • False
  • None

ఉదాహరణ

将 Python 对象转换为 JSON 字符串,并打印值:

import json
print(json.dumps({"name": "Bill", "age": 63}))
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": "Bill",
  "age": 63,
  "married": True,
  "divorced": False,
  "children": ("Jennifer","Rory","Phoebe"),
  "pets": None,
  "cars": [
    {"model": "Porsche", "mpg": 38.2},
    {"model": "BMW M5", "mpg": 26.9}
  }
}
}

ఉదాహరణను నడుపుము

print(json.dumps(x))

ఫలితం ఫార్మాట్

json.dumps() పై ఉదాహరణలో ఒక JSON స్ట్రింగ్ని ప్రచ్ఛదించబడింది, కానీ ఇది సులభంగా చదవగలిగే రీతిలో లేదు, పద్ధతి లో కాండాలు మరియు వాక్యం పందులు లేవు.

ఉదాహరణ

ఉపయోగం indent పారామీటర్లను నిర్దేశించడం ద్వారా పద్ధతిని సులభంగా చదవగలిగే పద్ధతిగా చేయడానికి పారామీటర్లను అందిస్తుంది:

json.dumps(x, indent=4)

ఉదాహరణను నడుపుము

మీరు కూడా విభజకాలను నిర్వచించవచ్చు, డిఫాల్ట్ విలువలు (", ", ": "), అనగా ప్రతి ఆబిజక్షన్ని కాండాలు మరియు స్పేస్ తో విభజించడం, కీలకాంశాన్ని మరియు విలువను కాండాలు మరియు స్పేస్ తో విభజించడం అని అర్థం వహిస్తుంది:

ఉదాహరణ

ఉపయోగం separators డిఫాల్ట్ విభజకాలను మార్చడానికి పారామీటర్లను నిర్దేశించండి:

json.dumps(x, indent=4, separators=(". ", " = "))

ఉదాహరణను నడుపుము

ఫలితాన్ని క్రమబద్ధం చేయండి

json.dumps() ఫలితంలోని కీలకాంశాలను క్రమబద్ధం చేయడానికి పారామీటర్లను అందిస్తుంది:

ఉదాహరణ

ఉపయోగం sort_keys ఫలితాన్ని క్రమబద్ధం చేయాలా అని నిర్ణయించడానికి పారామీటర్లను నిర్దేశించండి:

json.dumps(x, indent=4, sort_keys=True)

ఉదాహరణను నడుపుము