我试图解析从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=文本表示)?
既然PowerShell是跨平台的,我想我就把它扔到那里,因为我发现它相当直观和非常简单。
curl -s 'https://api.github.com/users/lambda' | ConvertFrom-Json
ConvertFrom-Json将JSON转换为PowerShell自定义对象,这样您就可以轻松地使用这些属性。例如,如果你只想要'id'属性,你只需要这样做:
curl -s 'https://api.github.com/users/lambda' | ConvertFrom-Json | select -ExpandProperty id
如果你想从Bash内部调用整个东西,那么你必须像这样调用它:
powershell 'curl -s "https://api.github.com/users/lambda" | ConvertFrom-Json'
当然,有一个纯粹的PowerShell方法来做它没有卷曲,这将是:
Invoke-WebRequest 'https://api.github.com/users/lambda' | select -ExpandProperty Content | ConvertFrom-Json
最后,还有ConvertTo-Json,它可以很容易地将自定义对象转换为JSON。这里有一个例子:
(New-Object PsObject -Property @{ Name = "Tester"; SomeList = @('one','two','three')}) | ConvertTo-Json
它会生成这样的JSON:
{
"Name": "Tester",
"SomeList": [
"one",
"two",
"three"
]
}
诚然,在Unix上使用Windows shell有点亵渎神明,但PowerShell确实擅长某些事情,解析JSON和XML就是其中之一。这是跨平台版本PowerShell的GitHub页面
更新(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
你有多种选择。
您可以使用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