在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 default
jq will pretty-print your JSON by default
jq默認會漂亮地打印您的JSON

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

JMESPath is a query language for JSON
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標準庫的一部分,這意味著您需要使用pippipenv安裝它。 例如, 在虛擬環境中 使用 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,一經查實,立即刪除!

相關文章

Vlan中Trunk接口配置

Vlan中Trunk接口配置 參考文獻:HCNA網絡技術實驗指南 模擬器:eNSP 實驗環境: 實驗目的:掌握Trunk端口配置 掌握Trunk端口允許所有Vlan配置方法 掌握Trunk端口允許特定Vlan配置方法 實驗拓撲: 實驗IP地址 :…

django中的admin組件

Admin簡介: Admin:是django的后臺 管理的wed版本 我們現在models.py文件里面建幾張表: class Author(models.Model):nid models.AutoField(primary_keyTrue)namemodels.CharField( max_length32)agemodels.IntegerField()# 與AuthorDetail建立一對一的關…

虛擬主機創建虛擬lan_創建虛擬背景應用

虛擬主機創建虛擬lanThis is the Part 2 of the MediaPipe Series I am writing.這是我正在編寫的MediaPipe系列的第2部分。 Previously, we saw how to get started with MediaPipe and use it with your own tflite model. If you haven’t read it yet, check it out here.…

.net程序員安全注意代碼及服務器配置

概述 本人.net架構師,軟件行業為金融資訊以及股票交易類的軟件產品設計開發。由于長時間被黑客攻擊以及騷擾。從事高量客戶訪問的服務器解決架構設計以及程序員編寫指導工作。特此總結一些.net程序員在代碼編寫安全以及服務器設置安全常用到的知識。希望能給對大家…

文件的讀寫及其相關

將軟件布置在第三方電腦上會出現無法提前指定絕對路徑的情況,這回影響到后續的文件讀寫;json文件是數據交換的一種基本方法,為了減少重復造輪子,經行標準化代碼。關于路徑: import os workspaceos.getcwd() pathos.pat…

接口測試框架2

現在市面上做接口測試的工具很多,比如Postman,soapUI, JMeter, Python unittest等等,各種不同的測試工具擁有不同的特色。但市面上的接口測試工具都存在一個問題就是無法完全吻合的去適用沒一個項目,比如數據的處理,加…

python 傳不定量參數_Python中的定量金融

python 傳不定量參數The first quantitative class for vanilla finance and quantitative finance majors alike has to do with the time value of money. Essentially, it’s a semester-long course driving notions like $100 today is worth more than $100 a year from …

axis為amchart左右軸的參數

<axis>left</axis> <!-- [left] (left/ right) indicates which y axis should be used --> <title>流通股</title> <!-- [] (graph title) --> <…

雷軍宣布紅米 Redmi 品牌獨立,這對小米意味著什么?

雷鋒網消息&#xff0c;1 月 3 日&#xff0c;小米公司宣布&#xff0c;將在 1 月 10 日召開全新獨立品牌紅米 Redmi 發布會。從小米公布的海報來看&#xff0c;Redmi 品牌標識出現的倒影中&#xff0c;有 4800 的字樣&#xff0c;這很容易讓人聯想起此前小米總裁林斌所宣布的 …

JAVA的rotate怎么用,java如何利用rotate旋轉圖片_如何在Java中旋轉圖形

I have drawn some Graphics in a JPanel, like circles, rectangles, etc.But I want to draw some Graphics rotated a specific degree amount, like a rotated ellipse. What should I do?解決方案If you are using plain Graphics, cast to Graphics2D first:Graphics2D …

貝葉斯 樸素貝葉斯_手動執行貝葉斯分析

貝葉斯 樸素貝葉斯介紹 (Introduction) Bayesian analysis offers the possibility to get more insights from your data compared to the pure frequentist approach. In this post, I will walk you through a real life example of how a Bayesian analysis can be perform…

vs2005 vc++ 生成非托管的 不需要.net運行環境的exe程序方法

在VS2005里開發的VC程序在編譯的時候&#xff0c;微軟默認會加入自己的 .Net Framework &#xff08;方便推廣自家產品&#xff09;&#xff0c;讓你的VC程序依賴它&#xff0c;這就導致程序編譯后&#xff0c;無法跟往常一樣直接打包&#xff0c;在別的機器就能正常運行。如果…

西工大java實驗報告給,西工大數字集成電路實驗 實驗課6 加法器的設計

西工大數字集成電路實驗練習六 加法器的設計一、使用與非門(NAND)、或非門(NOR)、非門(INV)等布爾邏輯器件實現下面的設計。1、仿照下圖的全加器&#xff0c;實現一個N位的減法器。要求仿照圖1畫出N位減法器的結構。ABABABAB0123圖1 四位逐位進位加法器的結構2、根據自己構造的…

DS二叉樹--二叉樹之數組存儲

二叉樹可以采用數組的方法進行存儲&#xff0c;把數組中的數據依次自上而下,自左至右存儲到二叉樹結點中&#xff0c;一般二叉樹與完全二叉樹對比&#xff0c;比完全二叉樹缺少的結點就在數組中用0來表示。&#xff0c;如下圖所示 從上圖可以看出&#xff0c;右邊的是一顆普通的…

VS IIS Express 支持局域網訪問

使用Visual Studio開發Web網頁的時候有這樣的情況&#xff1a;想要在調試模式下讓局域網的其他設備進行訪問&#xff0c;以便進行測試。雖然可以部署到服務器中&#xff0c;但是卻無法進行調試&#xff0c;就算是注入進程進行調試也是無法達到自己的需求&#xff1b;所以只能在…

前復權后復權程序C# .net

if (win32apitest.MDIMain.SFSDA.FuQuan "前復權") { if (mytime DateTime.Parse("2009-04-29")) { //if (svalue 34.89) …

一天一個js知識

原型繼承和class繼承 class&#xff1a;js中并不存在類的概念&#xff0c;class只是語法糖&#xff0c;本質還是函數&#xff1b; 提升&暫時性死區 console.log(a)// ? a() {} var a8 function a(){} 復制代碼 1、這里說明函數的提升要優先于變量的提升&#xff1b;函數提…

構建圖像金字塔_我們如何通過轉移學習構建易于使用的圖像分割工具

構建圖像金字塔Authors: Jenny Huang, Ian Hunt-Isaak, William Palmer作者&#xff1a; 黃珍妮 &#xff0c; 伊恩亨特伊薩克 &#xff0c; 威廉帕爾默 GitHub RepoGitHub回購 介紹 (Introduction) Training an image segmentation model on new images can be daunting, es…

PHP mongodb運用,MongoDB在PHP下的應用學習筆記

1、連接mongodb默認端口是&#xff1a;27017&#xff0c;因此我們連接mongodb&#xff1a;$mongodb new Mongo(localhost) 或者指定IP與端口 $mongodb new Mongo(192.168.127.1:27017) 端口可改變若mongodb開啟認證&#xff0c;即--auth,則連接為&#xff1a; $mongodb new …

a標簽

a標簽定義超鏈接&#xff0c;用于從一張頁面鏈接到另一張頁面&#xff0c;它最重要的屬性是 href 屬性&#xff0c;它指示鏈接的目標。 <a href"http://www.w3school.com.cn">W3School</a> 最常用的就像這樣添加一個鏈接&#xff0c;如果是點擊事件的話&…