如何在命令行中使用jq將JSON轉換為CSV

by Knut Melv?r

通過納特·梅爾瓦

如何在命令行中使用jq將JSON轉換為CSV (How to transform JSON to CSV using jq in the command line)

The shell tool jq is awesome for dealing with JSON-data. It can also transform that data into handy CSV-files, ready for all your spreadsheet wrangling needs.

外殼程序工具jq非常適合處理JSON數據。 它還可以將數據轉換為方便的CSV文件,從而可以滿足您所有電子表格的處理需求。

jq is an excellent little tool that lives in your terminal and does useful stuff with JSON-data. It’s a potent tool, but handy for the little things as well. For example, if you pipe JSON data to it, it prints it with syntax highlighting ? by default:

jq是一個出色的小工具,它駐留在您的終端中,并且可以處理JSON數據。 這是一個強大的工具,但對于一些小事情也很方便。 例如,如果您將JSON數據傳遞給它,它將以語法高亮顯示? 默認:

$ cat some-data.json|jq

$ cat some-data.json|jq

You can install jq on most systems. (brew install jq on a Mac with homebrew / chocolatey install jq on windows with chocolatey). This post presents a more advanced jq technique. If you want to get the basics, you should check out the tutorial.

您可以在大多數系統上安裝jq 。 ( brew install jq在裝有自制軟件的Mac上chocolatey install jq / chocolatey install jq在裝有Chocolatey的 Windows上chocolatey install jq )。 這篇文章介紹了一種更高級的jq技術。 如果您想了解基礎知識,則應該閱讀本教程 。

jq works with any JSON source. Since I’m spending most of my days working with Sanity.io-based backends, I’ll use that as an example. Also because I think it’s immensely cool what we can do with this combination.

jq可與任何JSON源一起使用。 由于我大部分時間都在使用基于Sanity.io的后端,因此我將以此為例。 同樣是因為我認為使用此組合可以做的事非常酷。

Sanity is a backend for structured content and comes with a real-time API, and a query language called GROQ. You can interact with Sanity via HTTP and JS/PHP clients, but also with the CLI tool with $ sanity documents query 'GROQ-expression'.

Sanity是結構化內容的后端,并帶有實時API和稱為GROQ的查詢語言。 您可以通過HTTP和JS / PHP客戶端與Sanity進行交互,也可以通過帶有$ sanity documents query 'GROQ-expression'的CLI工具進行$ sanity documents query 'GROQ-expression'

So if you want your documents of the type post, you put $ sanity documents query '*[_type == "post"]'. Or if you just want those with a publish date in 2018, it’s$ sanity documents query '*[_type == "post" && publishedAt > "2018-01-01"]'. This query gives you whole documents. If you just wanted the titles, and publish dates, you’d write: *[_type == "post"]{title, publishedAt}.

因此,如果您希望使用post類型的文檔,則可以將$ sanity documents query '*[_type == "post"]'放在$ sanity documents query '*[_type == "post"]' 。 或者,如果您只希望發布日期在2018年的$ sanity documents query '*[_type == "post" && publishedAt > "2018-01-01 ,則使用$ sanity documents query '*[_type == "post" && publishedAt > "2018-01-01 ”]“。 該查詢為您提供整個文檔。 如果您只想要標題并發布日期,則可以寫出e: *[_type == "post"]{title, published于}。

You can pick out keys and values from JSON data in jq as well. Today we’re going to use it to transform structured content in a JSON array to a CSV file. Because your boss wants stuff in Excel sheets, right? Sit tight, and let’s dive in! ??

您也可以從jq JSON數據中選擇鍵和值。 今天,我們將使用它來將JSON數組中的結構化內容轉換為CSV文件。 因為您的老板想要Excel工作表中的內容,對嗎? 坐好,讓我們開始吧! ?

Let’s say you want a list of your blog entries’ titles, slugs and publish dates in a spreadsheet. The whole expression would look like this:

假設您要在電子表格中列出博客條目的標題,條目和發布日期。 整個表達式如下所示:

sanity documents query '*[_type == "post"]{title, "slug": slug.current, publishedAt}'|jq -r '(map(keys) | add | unique) as $cols | map(. as $row | $cols | map($row[.])) as $rows | $cols, $rows[] | @csv'

You can copy this and run with it or play with it on jqplay.com, but let’s see what’s going on in the jq-expression:

您可以復制并運行它,也可以在jqplay.com上使用它 ,但是讓我們看看jq -expression中發生了什么:

  • -r is for --raw-ouput and makes sure that the output is plain old boring text without colors or special formatting.

    -r用于--raw-ouput ,并確保輸出為純舊的無聊文本,沒有顏色或特殊格式。

  • (map(keys) | add | unique) as $cols iterates (map) through the keys in your object and adds unique ones to a variable called $cols. In other words, this is how your column headers are made.

    (map(keys) | add | unique) as $cols迭代( map )通過你的對象和按鍵add小號unique的人給一個變量叫$cols 。 換句話說,這就是列標題的制作方式。

  • map(. as $row | $cols | map($row[.])) as $rows takes all objects in the outer array, and iterates through all the object keys (title, slug, publishedAt). It appends the values to an array, which gives you an array of arrays with the values, which is what you want when you're transforming JSON into CSV.

    map(. as $row | $cols | map($row[.])) as $rows獲取外部數組中的所有對象,并遍歷所有對象鍵(title,slug,publishedAt)。 它將值附加到數組,這將為您提供帶有值的數組數組,這是將JSON轉換為CSV時所需的值。

  • $cols, $rows[] | @csv puts the column headers first in the array, and then each of the arrays that are transformed to lines by piping them to @csv , which formats the output as… csv.

    $cols, $rows[] | @csv $cols, $rows[] | @csv將列標題放在數組中,然后通過將它們通過管道傳遞到@csv將每個數組轉換為行,從而將輸出格式為…csv。

This command prints out the result in the shell. If you want to write it directly to a file, you can append > filename.csv to it, or, for example, to the clipboard (pipe it to | pbcopy if you’re on macOS). Or perhaps you'll do something exciting with the csv in pandas ?? in Python?

此命令將結果打印到外殼中。 如果要直接將其寫入文件,可以附加> filename. csv,或例如剪貼板(如果您使用的是macOS,請將其to | pbc管道to | pbc pbc opy)。 也許您會在pan das中使用csv做一些令人興奮的事情? 在Python中?

If you found this useful, we'd love to hear all about it in the comment section!

如果您覺得此功能有用,我們很樂意在評論部分中聽到所有有關此信息的信息!

If you want to try out Sanity.io, you can go to sanity.io/freecodecamp and get an upped free developer plan. ?

如果您想試用Sanity.io,可以轉到sanity.io/freecodecamp并獲得升級的免費開發者計劃。 ?

Originally published at sanity.io.

最初在sanity.io上發布。

翻譯自: https://www.freecodecamp.org/news/how-to-transform-json-to-csv-using-jq-in-the-command-line-4fa7939558bf/

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/393545.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/393545.shtml
英文地址,請注明出處:http://en.pswp.cn/news/393545.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

macaca運行報錯之chrome-driver問題處理,關閉 Chrome 的自動更新

自動更新是 Chrome 非常實用的功能之一,但在有些情況下可能還是有關閉自動更新的需求,比如需要用某一個具體的版本來測試一些東西,或者更新之后反而出現了新的 Bug等等。由于一般人沒有這樣的需求,所以 Google 沒有公布關閉自動更…

docker啟動sqlserver_Docker搭建SQLServer

一、下載鏡像docker pull microsoft/mssql-server-linux二、啟動容器docker-composeversion: 3services:sqlserver:image: microsoft/mssql-server-linux:latestrestart: alwaysprivileged: truecontainer_name: sqlserverports:- 1433:1433volumes:- ./data:/var/opt/mssql/da…

【Python】 子進程創建與使用subprocess

subprocess *****本文參考了Vamei大神的http://www.cnblogs.com/vamei/archive/2012/09/23/2698014.html   運用subprocess包可以在運行python的進程下進一步開啟一個子進程,創建子進程要注意 1. 父進程是否暫停 2.創建出的子進程返回了什么 3.執行出錯&#xff0c…

異步查詢回調函數調用

異步查詢數據,需要對返回的數據進行后續步驟操作,使用使用方法: 1、new promise方法使用。 2、回調函數使用 使用方式:   pageGetDeviceTreeInfo({deviceTypeAry:[1]},this.getTreeData); 函數: 1 export function p…

前端開發從項目中獲得什么_我如何獲得副項目的前10個客戶以及從他們那里學到的東西...

前端開發從項目中獲得什么by Tigran Hakobyan由Tigran Hakobyan 我如何獲得副項目的前10個客戶以及從他們那里學到的東西 (How I got my first 10 customers for my side-project and what I’ve learned from them) My name is Tigran, I’m 29, and I’m the creator of Cro…

leetcode278. 第一個錯誤的版本(二分查找)

你是產品經理,目前正在帶領一個團隊開發新的產品。不幸的是,你的產品的最新版本沒有通過質量檢測。由于每個版本都是基于之前的版本開發的,所以錯誤的版本之后的所有版本都是錯的。 假設你有 n 個版本 [1, 2, …, n],你想找出導致…

lrzsz ??linux與windows互傳

2019獨角獸企業重金招聘Python工程師標準>>> lrzsz linux與windows互傳 # 前提是使用 xshell 或者 securecrt 這兩個遠程軟件,putty不支持 yum install -y lrzsz //安裝文件包 linux向windows 傳文件使用 : sz 文件名 回…

mysql show 命令_mysql show 相關命令

processlist的show方式是不能使用過濾查找,可能源自MySQL的內部安全機制吧,show是用來查看MySQL內部運行數據,其實processlist就是information_schema數據庫中的一張表,那么通過查表的方式肯定是可以的了:SELECT user,…

ordereddict有序字典

import collections as con# 有序添加和取字典元素 ord con.OrderedDict() ord[a] 1 ord[b] 2 ord[c] 3 print(ord, ordereddict)# 移動某元素到最后 ord.move_to_end(a) print(ord, move_to_end)轉載于:https://www.cnblogs.com/xh4528/p/6538700.html

Spring: (一) -- 春雨潤物之 核心IOC

作為一個Java人,想必都或多或少的了解過Spring。對于其優勢也能道個一二,諸如方便解耦、支持AOP編程、支持聲明式事務、方便測試等等。Spring也不僅僅局限于服務器端開發,它可以做非常多的事情,任何Java應用都可以在簡單性、可測試…

reactjs快速如夢_幫助您理解和創建ReactJS應用的快速指南

reactjs快速如夢此帖子分為2部分 (This Post is divided into 2 parts) The First Part demonstrates how to create a simple React app using ‘create-react-app’ CLI and explains the project structure. 第一部分演示了如何使用“ create-react-app” CLI創建簡單的Reac…

leetcode1351. 統計有序矩陣中的負數(二分查找)

給你一個 m * n 的矩陣 grid,矩陣中的元素無論是按行還是按列,都以非遞增順序排列。 請你統計并返回 grid 中 負數 的數目。 示例 1: 輸入:grid [[4,3,2,-1],[3,2,1,-1],[1,1,-1,-2],[-1,-1,-2,-3]] 輸出:8 解釋&a…

XUbuntu22.04之跨平臺音頻編輯工具(平替Audition):ocenaudio(二百零二)

加粗樣式 簡介: CSDN博客專家,專注Android/Linux系統,分享多mic語音方案、音視頻、編解碼等技術,與大家一起成長! 優質專欄:Audio工程師進階系列【原創干貨持續更新中……】🚀 優質專欄&#…

QueryList4采集-圖片本地化

QueryList4采集圖片本地化 //采集public function cai() {//采集的url地址$data QueryList::get(https://news.ke.com/sh/baike/0033/)->rules([title > [.LOGCLICK , text],content > [.summary , text],image > [.lj-lazy , data-original , ,function($res){//…

mysql 從服務器同步設置_mysql主從同步配置

1.為什么要主從同步?在Web應用系統中,數據庫性能是導致系統性能瓶頸最主要的原因之一。尤其是在大規模系統中,數據庫集群已經成為必備的配置之一。集群的好處主要有:查詢負載、數據庫復制備份等。其中Master負責寫操作的負載&…

int、long、long long取值范圍

short int 1個字節儲存 unsigned short int 0~255short int -128~127 int 2個字節儲存 unsigned int 0~4294967295 int 2147483648~2147483647 long 4個字節儲存 unsigned long 0~4294967295long 21…

每天一個LINUX命令(pwd)

每天一個LINUX命令(pwd) 基本信息 pwd: /bin/pwd,顯示當前路徑的絕對路徑 語法:pwd 應用程序位置 which pwd PWD作用 pwd --help或者man pwd PWD的使用 pwd 轉載于:https://www.cnblogs.com/shanshanliu/p/6542403.html

leetcode69. x 的平方根(二分法)

實現 int sqrt(int x) 函數。 計算并返回 x 的平方根,其中 x 是非負整數。 由于返回類型是整數,結果只保留整數的部分,小數部分將被舍去。 示例 1: 輸入: 4 輸出: 2 代碼 class Solution {public int mySqrt(int x) {int l0,rx;while (…

一個swiper 兩個分頁器的寫法【總結】

寫項目的時候&#xff0c;使用的是swiper插件呈現的效果是一個swiper要實現兩個分頁器&#xff0c;下面就來總結一下 以swiper3為例來寫&#xff0c;在頁面中引入jquery、swiper.min.js和swiper.min.css文件。 HTML結構&#xff1a; <div class"banner swiper-containe…

react路由守衛+重定向_React + Apollo:如何在重新查詢后進行重定向

react路由守衛重定向by Jun Hyuk Kim金俊赫 React Apollo&#xff1a;如何在重新查詢后進行重定向 (React Apollo: How to Redirect after Refetching a Query) GraphQL is hot, and for a good reason. In short, it is a query language that allows you to ask for exact…