我试图解析从curl请求返回的JSON,就像这样:

curl 'http://twitter.com/users/username.json' |
    sed -e 's/[{}]/''/g' | 
    awk -v k="text" '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}'

上面将JSON划分为多个字段,例如:

% ...
"geo_enabled":false
"friends_count":245
"profile_text_color":"000000"
"status":"in_reply_to_screen_name":null
"source":"web"
"truncated":false
"text":"My status"
"favorited":false
% ...

我如何打印一个特定的字段(由-v k=文本表示)?


当前回答

如果你安装了PHP解释器:

php -r 'var_export(json_decode(`curl http://twitter.com/users/username.json`, 1));'

例如:

我们有一个资源,提供JSON内容与国家的ISO代码:http://country.io/iso3.json,我们可以很容易地看到它在一个shell与curl:

curl http://country.io/iso3.json

但它看起来不是很方便,也不容易读。更好地解析JSON内容并看到可读的结构:

php -r 'var_export(json_decode(`curl http://country.io/iso3.json`, 1));'

这段代码将打印如下内容:

array (
  'BD' => 'BGD',
  'BE' => 'BEL',
  'BF' => 'BFA',
  'BG' => 'BGR',
  'BA' => 'BIH',
  'BB' => 'BRB',
  'WF' => 'WLF',
  'BL' => 'BLM',
  ...

如果你有嵌套数组,这个输出看起来会更好…

其他回答

更新(2020)

我使用外部工具(例如Python)时遇到的最大问题是,你必须处理包管理器和安装它们的依赖关系。

然而,现在我们有了jq作为一个独立的静态工具,很容易通过GitHub发布和Webi (webinstall.dev/jq)跨平台安装,我建议:

Mac、Linux:

curl -sS https://webi.sh/jq | bash

Windows 10:

curl.exe -A MS https://webi.ms/jq | powershell

小抄:https://webinstall.dev/jq

原(2011)

TickTick是一个用bash编写的JSON解析器(不到250行代码)。

以下是作者在他的文章《想象一个Bash支持JSON的世界》中的片段:

#!/bin/bash
. ticktick.sh

``
  people = {
    "Writers": [
      "Rod Serling",
      "Charles Beaumont",
      "Richard Matheson"
    ],
    "Cast": {
      "Rod Serling": { "Episodes": 156 },
      "Martin Landau": { "Episodes": 2 },
      "William Shatner": { "Episodes": 2 }
    }
  }
``

function printDirectors() {
  echo "  The ``people.Directors.length()`` Directors are:"

  for director in ``people.Directors.items()``; do
    printf "    - %s\n" ${!director}
  done
}

`` people.Directors = [ "John Brahm", "Douglas Heyes" ] ``
printDirectors

newDirector="Lamont Johnson"
`` people.Directors.push($newDirector) ``
printDirectors

echo "Shifted: "``people.Directors.shift()``
printDirectors

echo "Popped: "``people.Directors.pop()``
printDirectors

如果有人只想从简单的JSON对象中提取值,而不需要嵌套结构,那么甚至不需要离开Bash就可以使用正则表达式。

下面是我使用基于JSON标准的bash正则表达式定义的函数:

function json_extract() {
  local key=$1
  local json=$2

  local string_regex='"([^"\]|\\.)*"'
  local number_regex='-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?'
  local value_regex="${string_regex}|${number_regex}|true|false|null"
  local pair_regex="\"${key}\"[[:space:]]*:[[:space:]]*(${value_regex})"

  if [[ ${json} =~ ${pair_regex} ]]; then
    echo $(sed 's/^"\|"$//g' <<< "${BASH_REMATCH[1]}")
  else
    return 1
  fi
}

注意:对象和数组不支持作为值,但支持标准中定义的所有其他值类型。另外,只要具有完全相同的键名,无论对在JSON文档中有多深,都将匹配。

以OP为例:

$ json_extract text "$(curl 'http://twitter.com/users/username.json')"
My status

$ json_extract friends_count "$(curl 'http://twitter.com/users/username.json')"
245

如果你正在寻找一个本地Mac解决方案来解析JSON(没有外部库等…),那么这是为你。

此信息来自https://www.macblog.org/parse-json-command-line-mac/

简而言之,自从Mac OS Yosemite有一个运行苹果脚本的工具叫做osascript,但是如果你传递-l 'Javascript'标志,你可以运行Javascript !这就是所谓的使用JXA (JavaScript for Automation)。

下面是为我自己的项目读取JSON文件的示例。

DCMTK_JSON=$(curl -s https://formulae.brew.sh/api/bottle/dcmtk.json) # -s for silent mode
read -r -d '' JXA <<EOF
function run() {
  var json = JSON.parse(\`$DCMTK_JSON\`);
  return json.bottles.$2.url;
}
EOF
DOWNLOAD_URL=$( osascript -l 'JavaScript' <<< "${JXA}" )
echo "DOWNLOAD_URL=${DOWNLOAD_URL}"

这里所发生的是我们将函数的输出存储到变量JXA中。然后我们可以使用JSON.parse()简单地运行javascript来解析JSON内容。然后简单地将包含脚本的JXA变量传递给osascript工具,以便它可以运行javascript。在我的例子中,如果测试的话,$2指的是arm64_monterey。javascript立即运行的原因是特殊的run()函数,JXA将查找该函数并在完成时返回其输出。

注意EOF(文件的结尾)用于处理多行文本输入,并且结束的EOF前面不能有任何空格。

您可以通过简单地打开终端并键入下面的命令来测试这是否适合您

osascript -l 'JavaScript' -e 'var app = Application.currentApplication(); app.includeStandardAdditions = true; app.displayDialog("Hello from JavaScript!");

这应该会弹出一个从javascript说hello的窗口

你有多种选择。 您可以使用trdsql[1]来解析和转换JSON/CSV输入。以你为榜样;

trdsql "select attr1,attr2 from sample.json"

你也可以像SQL一样使用where子句。输出在CSV, JSON等。非常方便的工具。

根据我的经验,trdsql在处理属性嵌套值时有点问题,所以我在适当的时候使用qp[2]找到了一个解决方案。

cat sample.json | qp 'select attr1, attr2.detail.name where attr3=10'

注意这里没有FROM。

为了查看结果,您可以使用超快速命令行json查看器工具jless来查看输出[3]。

Clickhouse来了个新人。您可以从[4]中看到它的功能。

https://github.com/noborus/trdsql https://jless.io https://github.com/f5io/qp https://clickhouse.com/blog/extracting-converting-querying-local-files-with-sql-clickhouse-local

你可以尝试这样做-

curl -s 'http://twitter.com/users/jaypalsingh.json' | 
awk -F=":" -v RS="," '$1~/"text"/ {print}'