我已经足够老了,还记得我们认为XML将改变编程世界......然后JSON把我们从那个地狱中拯救出来。解析和查询JSON数据是我们所有编码的基本任务,但有时我只想用最少的麻烦在本地获得一些数据。我刚刚了解到一个非常棒的库,可以做到这一点:jq 。让我们来看看我们可以用jq 做的一些很酷的事情!
首先,通过像Homebrew这样的工具来安装jq 。
brew install jq
在安装了Homebrew和一个本地的actors.json 文件后,让我们开始工作,提取一些数据吧
// Using this JSON file:
// https://raw.githubusercontent.com/algolia/datasets/master/movies/actors.json
// Get the 10th item in an array
cat actors.json | jq '.[10]'
// {
// "name": "Dwayne Johnson",
// "rating": 1568,
// "image_path": "/akweMz59qsSoPUJYe7QpjAc2rQp.jpg",
// "alternative_name": "The Rock",
// "objectID": "551486400"
// }
// Get a property from the 10th item in array
// > "Dwayne Johnson"
// Get multiple items
jq '.[10:12]'
// Get items up to the 12th position
jq '.[:12]'
// Get items after the 12th position
jq '.[12:]'
// Get an array of properties from all objects
jq '.[].name'
// > ["William Shatner", "Will Ferrell", ...]
// Create an object with only properties I want
jq '{ name: .[].name, rating: .[].rating}'
// Built in functions!
jq 'sort'
jq 'length'
jq 'reverse'
有很多其他方法可以使用jq ,所以我强烈建议你查看JQ Select Explained。从JSON中选择元素。 在可预见的未来,我会把jq ,因为它将是非常宝贵的!