Python has two data types that, together, form the perfect tool for working with JSON: dictionaries and lists. Let's explore how to:
Python有两种数据类型,它们一起构成了使用JSON的理想工具: 字典和列表 。 让我们探索如何:
- load and write JSON 加载和编写JSON
- Pretty-print and validate JSON on the command line 在命令行上漂亮打印并验证JSON
- Do advanced queries on JSON docs by using JMESPath 使用JMESPath对JSON文档进行高级查询
1.解码JSON (1. Decoding JSON)
Python ships with a powerful and elegant JSON library. It can be imported with:
Python附带了功能强大且优雅的JSON库 。 它可以通过以下方式导入:
import json
Decoding a string of JSON is as simple as json.loads(…)
(short for load string).
解码JSON字符串就像json.loads(…)
(加载字符串的缩写json.loads(…)
一样简单。
It converts:
它转换为:
- objects to dictionaries 反对字典
- arrays to lists, 数组到列表,
- booleans, integers, floats, and strings are recognized for what they are and will be converted into the correct types in Python 布尔值,整数,浮点数和字符串可以识别其含义,并将在Python中转换为正确的类型
Any
null
will be converted into Python’sNone
type任何
null
都将转换为Python的None
类型
Here’s an example of json.loads
in action:
这是一个实际使用json.loads
的示例:
>>> import json
>>> jsonstring = '{"name": "erik", "age": 38, "married": true}'
>>> json.loads(jsonstring)
{'name': 'erik', 'age': 38, 'married': True}
2.编码JSON (2. Encoding JSON)
The other way around is just as easy. Use json.dumps(…)
(short for ‘dump to string) to convert a Python object consisting of dictionaries, lists, and other native types into a string:
反之亦然。 使用json.dumps(…)
(“转储为字符串”的缩写)将包含字典,列表和其他本机类型的Python对象转换为字符串:
>>> myjson = {'name': 'erik', 'age': 38, 'married': True}
>>> json.dumps(myjson)
'{"name": "erik", "age": 38, "married": true}'
This is the exact same document, converted back to a string! If you want to make your JSON document more readable for humans, use the indent option:
这是完全相同的文档,转换回字符串! 如果要使JSON文档更易被人类阅读,请使用indent选项:
>>> print(json.dumps(myjson, indent=2))
{
"name": "erik",
"age": 38,
"married": true
}
3.命令行用法 (3. Command-line usage)
The JSON library can also be used from the command-line, to validate and pretty-print your JSON:
JSON库也可以从命令行使用,以验证 JSON并进行漂亮打印 :
$ echo "{ \"name\": \"Monty\", \"age\": 45 }" | \
python3 -m json.tool
{
"name": "Monty",
"age": 45
}
As a side note: if you’re on a Mac or Linux and get the chance to install it, look into the jq
command-line tool too. It’s easy to remember, colorizes your output, and has loads of extra features as explained in my article on becoming a command-line ninja.
附带说明:如果您使用的是Mac或Linux,并且有机会安装它,请也查看jq
命令行工具。 正如我在成为命令行忍者中的文章中所解释的那样,它很容易记住,为您的输出着色,并具有许多额外的功能。
4.使用JMESPath搜索JSON (4. Searching through JSON with JMESPath)
JMESPath is a query language for JSON. It allows you to easily obtain the data you need from a JSON document. If you ever worked with JSON before, you probably know that it’s easy to get a nested value.
JMESPath是JSON的查询语言。 它使您可以轻松地从JSON文档中获取所需的数据。 如果您曾经使用过JSON,那么您可能知道获取嵌套值很容易。
For example: doc["person"]["age"]
will get you the nested value for age in a document that looks like this:
例如: doc["person"]["age"]
将为您提供文档的年龄嵌套值,如下所示:
{
"persons": {
"name": "erik",
"age": "38"
}
}
But what if you want to extract all the age-fields from an array of persons, in a document like this:
但是,如果您想从一系列人员中提取所有年龄段,在这样的文档中怎么办:
{
"persons": [
{ "name": "erik", "age": 38 },
{ "name": "john", "age": 45 },
{ "name": "rob", "age": 14 }
]
}
We could write a simple loop and loop over all the persons. Easy peasy. But loops are slow and introduce complexity to your code. This is where JMESPath comes in!
我们可以编写一个简单的循环,遍历所有人员。 十分简单。 但是循环很慢,会给您的代码带来复杂性。 这就是JMESPath进来的地方!
This JMESPath expression will get the job done:
这个JMESPath表达式将完成工作:
persons[*].age
It will return an array with all the ages: [38, 45, 14]
.
它将返回一个所有年龄的数组: [38, 45, 14]
。
Say you want to filter the list, and only get the ages for people named ‘erik’. You can do so with a filter:
假设您要过滤列表,仅获取名为“ erik”的人的年龄。 您可以使用过滤器执行此操作:
persons[?name=='erik'].age
See how natural and quick this is?
看看这有多自然和快速?
JMESPath is not part of the Python standard library, meaning you’ll need to install it with pip
or pipenv
. For example, when using pip
in in virtual environment:
JMESPath不是Python标准库的一部分,这意味着您需要使用pip
或pipenv
安装它。 例如, 在虚拟环境中 使用 pip
时:
$ pip3 install jmespath
$ python3
Python 3.8.2 (default, Jul 16 2020, 14:00:26)
>>> import jmespath
>>> j = { "people": [{ "name": "erik", "age": 38 }] }
>>> jmespath.search("people[*].age", j)
[38]
>>>
You’re now ready to start experimenting! Make sure to try the interactive tutorial and view the examples on the JMESPath site!
您现在就可以开始尝试了! 确保尝试交互式教程并在JMESPath站点上查看示例 !
If you have more JSON tips or tricks, please share them in the comments!Follow me on Twitter to get my latest articles first and make sure to visit my Python 3 Guide.
如果您还有其他JSON技巧或窍门,请在评论中分享! 在Twitter上 关注我 ,首先获取我的最新文章,并确保访问我的 Python 3指南 。
翻译自: https://towardsdatascience.com/4-tricks-to-effectively-use-json-in-python-4ca18c3f91d0
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/388719.shtml
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!