在 Bash 中解析 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33592758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:53:28  来源:igfitidea点击:

Parse JSON in Bash

jsonbashshellunixcurl

提问by Jérémie Zarca

I'm trying to get the value of a json array but I don't manage to get the value of a leaf, can anyone help me?

我正在尝试获取 json 数组的值,但无法获取叶子的值,有人可以帮助我吗?

Here's the json from maps.googleapis.com/maps/api

这是来自maps.googleapis.com/maps/api的 json

I'd like to get the duration text and value and here's the script I've been using so far.

我想获取持续时间文本和值,这是我迄今为止一直在使用的脚本。

function jsonValue() {
KEY=
num=
awk -F"[,:}]" '{for(i=1;i<=NF;i++){if($i~/'$KEY'2/){print $(i+1)}}}' | tr -d '"' | sed -n ${num}p
}

curl --get --include 'http://maps.googleapis.com/maps/api/directions/json?origin=59.94473,30.294254&destination=59.80612,30.308552&sensor=false&departure_time=1346197500&mode=transit&format=json'  | jsonValue duration["value"] 2

Thanks in advance,
Jeremie.

提前致谢,
杰瑞米。

回答by Ole Tange

You are looking for jq(a lightweight and flexible command-line JSON processor).

您正在寻找jq(轻量级且灵活的命令行 JSON 处理器)。

回答by Jérémie Zarca

This worked for me

这对我有用

curl -G -k --data "origin=59.94473,30.294254&destination=59.80612,30.308552&sensor=false&departure_time=1346197500&mode=transit" http://maps.googleapis.com/maps/api/directions/json | jq '.routes[].legs[].duration["text"]'