日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

在Python中有效使用JSON的4个技巧

發布時間:2023/11/29 javascript 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 在Python中有效使用JSON的4个技巧 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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’s None 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命令行工具。 正如我在成為命令行忍者中的文章中所解釋的那樣,它很容易記住,為您的輸出著色,并具有許多額外的功能。

jq will pretty-print your JSON by defaultjq默認會漂亮地打印您的JSON

4.使用JMESPath搜索JSON (4. Searching through JSON with JMESPath)

Screenshot by author截圖

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

總結

以上是生活随笔為你收集整理的在Python中有效使用JSON的4个技巧的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。