Python Parse JSON –转储,加载

这篇教程介绍了Python中的JSON处理,包括如何使用json模块进行数据编码和解码。内容涵盖Python json.dumps用于转储JSON数据,json.loads用于解析JSON数据,以及Python对象与JSON数据之间的转换规则。
摘要由CSDN通过智能技术生成

In this tutorial we will be discussing on Python JSON; how to encode and decode JSON data using python. In our previous tutorial we discussed about Python raw_input.

在本教程中,我们将讨论Python JSON。 如何使用python编码和解码JSON数据。 在之前的教程中,我们讨论了有关Python raw_input的问题

Python JSON (Python JSON)

Before starting with the Python’s json module, we will at first discuss about JSON data.

在开始使用Python的json模块之前,我们将首先讨论JSON数据。

The abbreviation of JSON is JavaScript Object Notation.

JSON的缩写是的J ava 小号 CRIPTöbjectÑ浮选。

According to Wikipedia, JSON is an open-standard file format that uses human-readable text to transmit data objects consisting of attribute-value pairs and array data types (or any other serializable value).

根据Wikipedia的说法,JSON是一种开放标准的文件格式,它使用人类可读的文本来传输由属性值对和数组数据类型(或任何其他可序列化的值)组成的数据对象。

JSON a very common data format used for asynchronous browser/server communication. The Syntax rules for JSON is given below:

JSON是一种非常常见的数据格式,用于异步浏览器/服务器通信。 JSON的语法规则如下:

  1. The data is simply a name value pair

    数据只是一个名称值对
  2. Data/Object/arrays are separated by comma

    数据/对象/数组用逗号分隔
  3. Curly braces hold object

    花括号支撑对象
  4. Square holds array

    方阵

You may see some JSON data example here.

您可能会在这里看到一些JSON数据示例。

Python json转储 (Python json dumps)

In this section we will learn how to convert python data to JSON data. The task is very simple. At first import json module. Then use json.dumps() function to decode the json data. Below is a simple example for python json dumps function.

在本节中,我们将学习如何将python数据转换为JSON数据。 任务很简单。 首先导入json模块。 然后使用json.dumps()函数解码json数据。 以下是python json转储函数的简单示例。

import json

# initialize different data
str_data = 'normal string'
int_data = 1
float_data = 1.50
list_data = [str_data, int_data, float_data]
nested_list = [int_data, float_data, list_data]
dictionary = {
    'int': int_data,
    'str': str_data,
    'float': float_data,
    'list': list_data,
    'nested list': nested_list
}

# convert them to JSON data and then print it
print('String :', json.dumps(str_data))
print('Integer :', json.dumps(int_data))
print('Float :', json.dumps(float_data))
print('List :', json.dumps(list_data))
print('Nested List :', json.dumps(nested_list, indent=2))
print('Dictionary :', json.dumps(dictionary, indent=2))  # the json data will be indented

You will get output like this.

您将获得这样的输出。

String : "normal string"
Integer : 1
Float : 1.5
List : ["normal string", 1, 1.5]
Nested List : [
  1,
  1.5,
  [
    "normal string",
    1,
    1.5
  ]
]
Dictionary : {
  "int": 1,
  "str": "normal string",
  "float": 1.5,
  "list": [
    "normal string",
    1,
    1.5
  ],
  "nested list": [
    1,
    1.5,
    [
      "normal string",
      1,
      1.5
    ]
  ]
}

Python JSON漂亮打印 (Python JSON pretty print)

As you can see in above example, for json pretty print we have to pass an extra variable ‘indent’ to the json dumps function. For example json.dumps(nested_list, indent=2).

如您在上面的示例中看到的那样,对于json漂亮打印,我们必须将一个额外的变量'indent'传递给json转储函数。 例如json.dumps(nested_list, indent=2)

Python解析json – python json加载 (Python parse json – python json loads)

You can easily parse JSON data to Python objects. By using json.loads() function you can simply convert JSON data into Python data. So, see the following python parse json example code to understand python json loads function.

您可以轻松地将JSON数据解析为Python对象。 通过使用json.loads()函数,您可以简单地将JSON数据转换为Python数据。 因此,请参阅以下python parse json示例代码以了解python json加载功能。

import json

# initialize different JSON data
arrayJson = '[1, 1.5, ["normal string", 1, 1.5]]'
objectJson = '{"a":1, "b":1.5 , "c":["normal string", 1, 1.5]}'

# convert them to Python Data
list_data = json.loads(arrayJson)
dictionary = json.loads(objectJson)

print('arrayJson to list_data :\n', list_data)
print('\nAccessing the list data :')
print('list_data[2:] =', list_data[2:])
print('list_data[:1] =', list_data[:1])

print('\nobjectJson to dictionary :\n', dictionary)
print('\nAccessing the dictionary :')
print('dictionary[\'a\'] =', dictionary['a'])
print('dictionary[\'c\'] =', dictionary['c'])

Below is the output of python parse json example program.

以下是python parse json示例程序的输出。

arrayJson to list_data :
 [1, 1.5, ['normal string', 1, 1.5]]

Accessing the list data :
list_data[2:] = [['normal string', 1, 1.5]]
list_data[:1] = [1]

objectJson to dictionary :
 {'a': 1, 'b': 1.5, 'c': ['normal string', 1, 1.5]}

Accessing the dictionary :
dictionary['a'] = 1
dictionary['c'] = ['normal string', 1, 1.5]

Python对象到JSON数据转换 (Python Object to JSON Data Conversion)

In the previous two sections you may have noticed that Python List is converted into JSONArray data and Python Dictionary becomes the JSONObject. So which Python object is converted into JSON object by default is shown in the below table.

在前两节中,您可能已经注意到Python列表已转换为JSONArray数据,而Python字典成为JSONObject 。 下表显示了默认情况下哪个Python对象转换为JSON对象。

PythonJSON
dictobject
list, tuplearray
strstring
int, float, int- & float-derived Enumsnumber
Truetrue
Falsefalse
Nonenull
Python JSON格式
字典 目的
列表,元组 数组
力量
int,float,int和float枚举
真正 真正
没有 空值

Also, if you convert a JSONArray, you will get Python List. So, there are also some rules about this. So the following tables show the type of JSON data that are converted into Python Data.

另外,如果您转换JSONArray,则会获得Python列表。 因此,对此也有一些规则。 因此,下表显示了转换为Python数据的JSON数据的类型。

JSONPython
objectdict
arraylist
stringstr
number (int)int
number (real)float
trueTrue
falseFalse
JSON格式 Python
目的 字典
数组 清单
力量
数字(整数) 整型
数字(实数) 浮动
真正 真正

So, that’s all about Python JSON module, python parse json examples. For any further query, please ask that in the comment section.

所以,这一切都与Python JSON模块,python解析json示例有关。 如有其他查询,请在评论部分中提出。

翻译自: https://www.journaldev.com/16016/python-parse-json-dumps-loads

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值