There are a number of tools specifically designed for the purpose of manipulating JSON from the command line, and will be a lot easier and more reliable than doing it with Awk, such as jq
:
(有许多专门用于从命令行操作JSON的工具,它们比使用Awk进行操作要容易得多,也更可靠,例如jq
:)
curl -s 'https://api.github.com/users/lambda' | jq -r '.name'
You can also do this with tools that are likely already installed on your system, like Python using the json
module , and so avoid any extra dependencies, while still having the benefit of a proper JSON parser.
(您也可以使用系统上可能已经安装的工具(例如使用json
模块的 Python)来执行此操作,从而避免任何额外的依赖关系,同时仍然可以使用适当的JSON解析器。)
The following assume you want to use UTF-8, which the original JSON should be encoded in and is what most modern terminals use as well: (以下假设您要使用UTF-8,原始JSON应该用UTF-8编码,这也是大多数现代终端所使用的:)
Python 2:
(Python 2:)
export PYTHONIOENCODING=utf8
curl -s 'https://api.github.com/users/lambda' |
python -c "import sys, json; print json.load(sys.stdin)['name']"
Python 3:
(Python 3:)
curl -s 'https://api.github.com/users/lambda' |
python3 -c "import sys, json; print(json.load(sys.stdin)['name'])"
Historical notes (历史笔记)
This answer originally recommended jsawk , which should still work, but is a little more cumbersome to use than jq
, and depends on a standalone JavaScript interpreter being installed which is less common than a Python interpreter, so the above answers are probably preferable:
(这个答案最初推荐jsawk ,它仍然可以工作,但是使用起来比jq
麻烦一些,并且取决于安装的独立JavaScript解释器,它比Python解释器少见,因此上述答案可能更可取:)
curl -s 'https://api.github.com/users/lambda' | jsawk -a 'return this.name'
This answer also originally used the Twitter API from the question, but that API no longer works, making it hard to copy the examples to test out, and the new Twitter API requires API keys, so I've switched to using the GitHub API which can be used easily without API keys.
(这个答案最初也使用了问题中的Twitter API,但是该API不再有效,因此很难复制示例进行测试,而新的Twitter API需要API密钥,因此我改用了GitHub API无需API密钥即可轻松使用。)
The first answer for the original question would be: (原始问题的第一个答案是:)
curl 'http://twitter.com/users/username.json' | jq -r '.text'