使用 bash 从 JSON 文件中提取数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34255260/
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 14:01:34  来源:igfitidea点击:

Extract data from JSON file using bash

jsonbashshell

提问by Thodoris

Let's say that we have this kind of JSON file:

假设我们有这种 JSON 文件:

{
  ... 
  "quotes":{
     "SOMETHING":10,
     ...
     "SOMETHING_ELSE":120.4,
     ...
  }   }

How can I obtain those values and use them in order to add them together?

我怎样才能获得这些值并使用它们来将它们加在一起?

Am I able to do even this?

我什至能做到这一点吗?

#!/bin/bash

#code ...

echo "$SOMETHING + $SOMETHING_ELSE" | bc

#code ...

#exit

I will obtain the JSON file with wget command. All I want is the content from this file.

我将使用 wget 命令获取 JSON 文件。我想要的只是这个文件的内容。

Can you help me, please? I am a beginner in shell programming.

你能帮我吗?我是 shell 编程的初学者。

回答by Giuseppe Ricupero

I usually use jq, a really fast json parser, to do this kind of things (because parsing a json file with tools like awkor sedis really error-prone).

我通常使用jq,一个非常快速的 json 解析器,来做这种事情(因为使用像awkor 之类的工具解析 json 文件sed真的很容易出错)。

Given an input file like this:

给定一个这样的输入文件:

# file: input.json
{
  "quotes":{
    "SOMETHING":10,
    "SOMETHING_ELSE":120.4
  }
}

You can obtain the sum of the 2 fields with a simple filter:

您可以使用简单的过滤器获取 2 个字段的总和:

jq '.quotes.SOMETHING + .quotes.SOMETHING_ELSE' input.json
# output -> 130.4

NOTE: jqis available in every major linux distribution. In a debian-derivative system you can install with a sudo apt-get install jq.

注意jq在每个主要的 linux 发行版中都可用。在 debian 衍生系统中,您可以使用sudo apt-get install jq.

回答by Erik Bryer

This will print out the sum of the selected lines' floats.

这将打印出所选行浮点数的总和。

#!/bin/bash
awk '{ if ( ~ /"SOMETHING":/) {print}; if ( ~ /"SOMETHING_ELSE":/) {print} }'  | cut -d: -f2 | cut -d, -f1 | awk '{s+=};END{print s}'

This finds the lines you want, the plucks out the numbers, and adds them.

这将找到您想要的行,提取数字并添加它们。

回答by Ewan Mellor

You should look up and learn jqas shown in Read the json data in shell script.

您应该jq按照Read the json data in shell script 中的说明查找并学习。

The tools in a "normal" shell installation like awk and sed all predate JSON by decades, and are a very very bad fit. jqis worth the time to learn.

像 awk 和 sed 这样的“普通”shell 安装中的工具都比 JSON 早了几十年,并且非常非常不合适。 jq值得花时间学习。

Or use Python instead.

或者改用 Python。