首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

什么是JSON?

JSON是数据交换的标准格式,它受JavaScript启发。通常,JSON是字符串或文本格式。JSON代表Ĵ AVA 小号 CRIPT ö bject Ñ浮选。

JSON的语法:JSON被编写为键和值对。

代码语言:javascript
复制
{
 "Key":  "Value",
 "Key":  "Value",} 

JSON与 Python字典非常相似。Python支持JSON,并且具有内置库作为JSON。

Python中的JSON库

Python的“ marshal ”和“ pickle”外部模块维护一个JSON库版本。要在Python中执行与JSON相关的操作(如编码和解码),您首先需要导入 JSON库,然后将其导入.py文件中,

代码语言:javascript
复制
import json

JSON模块中提供以下方法

代码语言:javascript
复制
方法  描述
dumps()  编码为JSON对象
dump()  编码的字符串写在文件上
loads()  解码JSON字符串
load()  读取JSON文件时解码

Python到JSON(编码)

Python的JSON库默认执行以下将Python对象转换为JSON对象的操作

Python

JSON

dict

Object

list

Array

unicode

String

number - int, long

number – int

float

number – real

True

True

False

False

None

Null

将Python数据转换为JSON称为编码操作。借助JSON库方法– dumps()进行编码

dumps()方法将python的字典对象转换为JSON字符串数据格式。

现在让我们使用Python执行第一个编码示例。

代码语言:javascript
复制
import json 

x = { 
  “ name”:“ Ken”,
  “ age”:45,
  “ married”:True,
  “ children”:(“ Alice”,“ Bob”),
  “ pets”:['Dog'],
  “ cars“:[ 
    {” model“:” Audi A1“,” mpg“:15.1},
    {” model“:” Zeep Compass“,” mpg“:18.1} 
  ] 
} 
#按键
升序排列结果:sorted_string = json.dumps(x,indent = 4,sort_keys = True)
打印(sorted_string)

输出:

代码语言:javascript
复制
{“ person”:{“ name”:“ Kenn”,“ sex”:“ male”,“ age”:28}})

让我们使用相同的函数dump()创建字典的JSON文件

代码语言:javascript
复制
# here we create new data_file.json file with write mode using file i/o operation 
with open('json_file.json', "w") as file_write:
# write json data into file
json.dump(person_data, file_write)

输出:

什么也没显示……在您的系统中创建json_file.json时,您可以检查该文件。

下一篇
举报
领券