如何使用jsawk在bash中解析多维JSON数组?

问题描述 投票:0回答:2

我有一个如下数组。我想将整个数据解析到我的bash数组中。因此,我可以从$ {bashaddr [0]}等中调用第一个“ JSON addressLineOne”,等等。

[
{
"id":"f0c546d5-0ce4-55ee-e043-516e0f0afdc1",
"cardType":"WMUSGESTORECARD",
"lastFour":"1682",
"cardExpiryDate":"2012-01-16",
"firstName":"robert",
"lastName":"robishaw",
"addressLineOne":"Apt venue",
"addressLineTwo":"",
"city":"oakdale",
"state":"CT",
"postalCode":"06370",
"phone":"534534",
"isDefault":false
},
{
"id":"f0c546d5-0ce0-55ee-e043-516e0f0afdc1",
"cardType":"MASTERCARD",
"lastFour":"2731",
"cardExpiryDate":"2009-08-31",
"firstName":"robert",
"lastName":"robishaw",
"addressLineOne":"119 maple ave.",
"addressLineTwo":"",
"city":"uncasville",
"state":"CT",
"postalCode":"06382",
"phone":"7676456",
"isDefault":false
},
{
"id":"f0c546d5-0ce2-55ee-e043-516e0f0afdc1",
"cardType":"MASTERCARD",
"lastFour":"6025",
"cardExpiryDate":"2011-08-31",
"firstName":"robert",
"lastName":"robishaw",
"addressLineOne":"Angeline Street",
"addressLineTwo":"",
"city":"oakdale",
"state":"CT",
"postalCode":"06370",
"phone":"7867876",
"isDefault":false
}

]

我尝试过这样:

#!/bin/bash
addressLineOne="$(echo $card | jsawk 'return this.addressLineOne')"

但是它给了我完整的地址:

["address 1","address 2","address 3"]

谢谢。

json bash multidimensional-array jsawk
2个回答
1
投票

我在阅读评论之前在下面写下了答案,但这与提供的@ 4ae1e1完全相同,不同之处在于,我不放置-r标记,以防您希望将值保留为引号(例如,将其作为参数传递)其他地方)。

我知道这不是jsawk,但请考虑jq

jq '.[].addressLineOne' yourfile.txt

要访问特定值,您可以将记录号放在方括号中(第一个地址以0开头,依此类推)。例如,获取第三条记录的地址:

jq '.[2].addressLineOne' yourfile.txt

要了解有关jq和高级用途的更多信息,请检查:http://jqplay.org


0
投票

您需要做的是利用-a开关进行一些后处理并过滤输出数组,如下所示:jsawk 'return this.addressLineOne' -a 'return this[0]'从文档中:

-b <script> | -a <script>
      Run the specified snippet of JavaScript before (-b) or after (-a)
      processing JSON input. The `this` object is set to the whole JSON
      array or object. This is used to preprocess (-b) or postprocess
      (-a) the JSON array before or after the main script is applied.
      This option can be specified multiple times to define multiple
      before/after scripts, which will be applied in the order they
      appeared on the command line.
© www.soinside.com 2019 - 2024. All rights reserved.