什么是JSON?

it2024-10-04  39

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

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

{  "Key":  "Value",  "Key":  "Value",} 

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

Python中的JSON库

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

import json

JSON模块中提供以下方法

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

Python到JSON(编码)

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

PythonJSONdictObjectlistArrayunicodeStringnumber - int, longnumber – intfloatnumber – realTrueTrueFalseFalseNoneNull

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

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

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

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)

输出:

{“ person”:{“ name”:“ Kenn”,“ sex”:“ male”,“ age”:28}})

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

# 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时,您可以检查该文件。

更多精彩推荐,请关注我们

扫码关注更多精彩

你点的每个赞,我都认真当成了喜欢

最新回复(0)