Unix 命令行 JSON 解析器?

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

Unix command-line JSON parser?

jsonparsingunixconfiguration

提问by Jé Queue

Can anyone recommend a Unix (choose your flavor) JSON parser that could be used to introspect values from a JSON response in a pipeline?

任何人都可以推荐一个 Unix(选择你的风格)JSON 解析器,它可以用于从管道中的 JSON 响应中内省值?

采纳答案by Ether

You can use this command-line parser (which you could put into a bash alias if you like), using modules built into the Perl core:

您可以使用这个命令行解析器(如果您愿意,可以将其放入 bash 别名中),使用 Perl 核心中内置的模块:

perl -MData::Dumper -MJSON::PP=from_json -ne'print Dumper(from_json($_))'

回答by muhqu

I prefer python -m json.toolwhich seems to be available per default on most *nix operating systems per default.

我更喜欢python -m json.tool默认情况下在大多数 *nix 操作系统上默认可用。

$ echo '{"foo":1, "bar":2}' | python -m json.tool
{
    "bar": 2, 
    "foo": 1
}

But it should be noted that this will sort all keys alphabetically, which is or can be a good thing in where the json was generated by some language that used unordered HashMaps...

但应该注意的是,这将按字母顺序对所有键进行排序,这在 json 是由使用无序 HashMap 的某种语言生成的地方或可能是一件好事......

回答by Daan Mortier

If you're looking for a portable C compiled tool:

如果您正在寻找可移植的 C 编译工具:

http://stedolan.github.com/jq/

http://stedolan.github.com/jq/

From the website:

从网站:

jq is like sedfor JSON data - you can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grepand friends let you play with text.

jq can mangle the data format that you have into the one that you want with very little effort, and the program to do so is often shorter and simpler than you'd expect.

JQ是一样的sed的JSON数据-你可以用它来切片和过滤器和地图,并与同样方便的是变换结构化数据的sedawk中grep的朋友让你用文字游戏。

jq 可以轻松地将您拥有的数据格式转换为您想要的格式,并且执行此操作的程序通常比您预期的更短更简单。

Tutorial: http://stedolan.github.com/jq/tutorial/
Manual: http://stedolan.github.com/jq/manual/
Download: http://stedolan.github.com/jq/download/

教程http: //stedolan.github.com/jq/tutorial/
手册http: //stedolan.github.com/jq/manual/
下载http: //stedolan.github.com/jq/download/

回答by Dave Dopson

I have created a module specifically designed for command-line JSON manipulation:

我创建了一个专门为命令行 JSON 操作设计的模块:

https://github.com/ddopson/underscore-cli

https://github.com/ddopson/underscore-cli

  • FLEXIBLE- THE "swiss-army-knife" tool for processing JSON data - can be used as a simple pretty-printer, or as a full-powered Javascript command-line
  • POWERFUL- Exposes the full power and functionality of underscore.js (plus underscore.string)
  • SIMPLE- Makes it simple to write JS one-liners similar to using "perl -pe"
  • CHAINED- Multiple command invokations can be chained together to create a data processing pipeline
  • MULTI-FORMAT- Rich support for input / output formats - pretty-printing, strict JSON, etc [coming soon]
  • DOCUMENTED- Excellent command-line documentation with multiple examples for every command
  • 灵活- 用于处理 JSON 数据的“瑞士军刀”工具 - 可用作简单的漂亮打印机,或用作功能齐全的 Javascript 命令行
  • POWERFUL- 展示 underscore.js(加上 underscore.string)的全部功能和功能
  • 简单- 使编写类似于使用“perl -pe”的 JS one-liners 变得简单
  • CHAINED- 多个命令调用可以链接在一起以创建数据处理管道
  • 多格式- 对输入/输出格式的丰富支持 - 漂亮的打印、严格的 JSON 等 [即将推出]
  • DOCUMENTED- 优秀的命令行文档,每个命令都有多个示例

It allows you to do powerful things really easily:

它可以让你非常轻松地做强大的事情:

cat earthporn.json | underscore select '.data .title'
# [ 'Fjaerárgljúfur canyon, Iceland [OC] [683x1024]',
#   'New town, Edinburgh, Scotland [4320 x 3240]',
#   'Sunrise in Bryce Canyon, UT [1120x700] [OC]',
# ...
#   'Kariega Game Reserve, South Africa [3584x2688]',
#   'Valle de la Luna, Chile [OS] [1024x683]',
#   'Frosted trees after a snowstorm in Laax, Switzerland [OC] [1072x712]' ]

cat earthporn.json | underscore select '.data .title' | underscore count
# 25

underscore map --data '[1, 2, 3, 4]' 'value+1'
# prints: [ 2, 3, 4, 5 ]

underscore map --data '{"a": [1, 4], "b": [2, 8]}' '_.max(value)'
# [ 4, 8 ]

echo '{"foo":1, "bar":2}' | underscore map -q 'console.log("key = ", key)'
# key = foo
# key = bar

underscore pluck --data "[{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}]" name
# [ 'moe', 'larry', 'curly' ]

underscore keys --data '{name : "larry", age : 50}'
# [ 'name', 'age' ]

underscore reduce --data '[1, 2, 3, 4]' 'total+value'
# 10

And it has one of the best "smart-whitespace" JSON formatters available:

它拥有最好的“智能空白”JSON 格式化程序之一:

If you have any feature requests, comment on this post or add an issue in github. I'd be glad to prioritize features that are needed by members of the community.

如果您有任何功能请求,请在此帖子上发表评论或在 github 中添加问题。我很乐意优先考虑社区成员需要的功能。

回答by CoolAJ86

Checkout TickTick.

结帐TickTick

It's a true Bash JSON parser.

这是一个真正的 Bash JSON 解析器。

#!/bin/bash
. /path/to/ticktick.sh

# File
DATA=`cat data.json`
# cURL
#DATA=`curl http://foobar3000.com/echo/request.json`

tickParse "$DATA"

echo ``pathname``
echo ``headers["user-agent"]``

回答by zpoley

There is also JSON command line processing toolkitif you happen to have node.js and npm in your stack.

如果您的堆栈中碰巧有 node.js 和 npm,那么还有JSON 命令行处理工具包

And another "json" commandfor massaging JSON on your Unix command line.

另一个“json”命令用于在您的 Unix 命令行上按摩 JSON。

And here are the other alternatives:

以下是其他选择:



Related: Command line tool for parsing JSON input for Unix?

相关:用于解析 Unix JSON 输入的命令行工具?

回答by hewigovens

Anyone mentioned Jshon or JSON.sh?

有人提到过 Jshon 或 JSON.sh 吗?

https://github.com/keenerd/jshon

https://github.com/keenerd/jshon

pipe json to it, and it traverses the json objects and prints out the path to the current object (as a JSON array) and then the object, without whitespace.

通过管道将 json 传递给它,它遍历 json 对象并打印出当前对象的路径(作为 JSON 数组),然后是对象,没有空格。

http://kmkeen.com/jshon/
Jshon loads json text from stdin, performs actions, then displays the last action on stdout and also was made to be part of the usual text processing pipeline.

http://kmkeen.com/jshon/
Jshon 从 stdin 加载 json 文本,执行操作,然后在 stdout 上显示最后一个操作,并且还成为常用文本处理管道的一部分。

回答by NG.

You could try jsawkas suggested in this answer.

您可以按照此答案中的建议尝试jsawk

Really you could whip up a quick python script to do this though.

不过,您确实可以编写一个快速的 Python 脚本来执行此操作。

回答by Aaron R.

For Bash/Python, here is a basic wrapper around python's simplejson:

对于Bash/Python,这是一个围绕 python 的基本包装器simplejson

json_parser() {
    local jsonfile="my_json_file.json"
    local tc="import simplejson,sys; myjsonstr=sys.stdin.read(); "`
            `"myjson=simplejson.loads(myjsonstr);"
    # Build python print command based on $@
    local printcmd="print myjson"
    for (( argn=1; argn<=$#; argn++ )); do
        printcmd="$printcmd['${!argn}']"
    done
    local result=$(python -c "$tc $printcmd.keys()" <$jsonfile 2>/dev/null \
        || python -c "$tc $printcmd" <$jsonfile 2>/dev/null)
    # For returning space-separated values
    echo $result|sed -e "s/[]|[|,|']//g"
    #echo $result 
}

It really only handles the nested-dictionary style of data, but it works for what I needed, and is useful for walking through the json. It could probably be adapted to taste.

它实际上只处理嵌套字典样式的数据,但它适用于我所需要的,并且对于遍历 json 很有用。它可能可以适应口味。

Anyway, something homegrown for those not wanting to source in yet another external dependency. Except for python, of course.

无论如何,对于那些不想在另一个外部依赖中进行采购的人来说,这是一种本土化的东西。当然,python 除外。

Ex. json_parser {field1} {field2}would run print myjson['{field1}']['{field2}'], yielding either the keys or the values associated with {field2}, space-separated.

前任。json_parser {field1} {field2}将运行print myjson['{field1}']['{field2}'],产生与{field2},空格分隔的键或值。

回答by Arthur

I just made jkidwhich is a small command-line json explorer that I made to easily explore big json objects. Objects can be explored "transversally" and a "preview" option is there to avoid console overflow.

我刚刚制作了jkid,它是一个小型的命令行 json 资源管理器,用于轻松探索大型 json 对象。可以“横向”探索对象,并且可以使用“预览”选项来避免控制台溢出。

$  echo '{"john":{"size":20, "eyes":"green"}, "bob":{"size":30, "eyes":"brown"}}' > test3.json
$  jkid . eyes test3.json 
object[.]["eyes"]
{
  "bob": "brown", 
  "john": "green"
}