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.pswp.cn/news/388719.shtml 繁體地址,請注明出處:http://hk.pswp.cn/news/388719.shtml 英文地址,請注明出處:http://en.pswp.cn/news/388719.shtml
如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!