简体   繁体   English

使用jq解析JSON文件

[英]JSON file parsing using jq

I have a JSON file with such detailes in it(not full file): 我有一个带有这样的detailes的JSON文件(不是完整文件):

{"property": [
    {

 {
      "name": "test1",
      "value": "{\"test_type\":\"jsystem\",\"order\":1,\"test_id\":\"test_01\",\"physical_setup_id\":\"prd_01\",\"timeout\":\"20\"}",
      "own": true
    },
   {
      "name": "test2",
      "value": "{\"test_type\":\"jsystem\",\"order\":2,\"test_id\":\"test_02\",\"physical_setup_id\":\"prd_02\",\"timeout\":\"30\"}",
      "own": true
    },
   {
      "name": "pass",
      "value": "{\"test_type\":\"jsystem\",\"order\":3,\"test_id\":\"test_03\",\"physical_setup_id\":\"prd_01\",\"timeout\":\"15\"}",
      "own": true
    }
 ]
}

And I am trying to extract all the fields that are contain "name test%NUMBER%" I've tried this: cat build.json | jq '.property | .[] | select(.name=="test1")' 我尝试提取包含“ name test%NUMBER%”的所有字段,我尝试这样做: cat build.json | jq '.property | .[] | select(.name=="test1")' cat build.json | jq '.property | .[] | select(.name=="test1")' cat build.json | jq '.property | .[] | select(.name=="test1")' - it works OK , but I want to add digital parameter to .name==test. cat build.json | jq '.property | .[] | select(.name=="test1")' -正常,但是我想向.name == test添加数字参数。 Something like this: 像这样:

cat build.json | jq '.property | .[] | select(.name=="test'[0-9]'")'

Ans second I need to parse each data under "value" parameter. 秒钟,我需要解析“值”参数下的每个数据。 Like this: 像这样:

test1:
test_type=jsystem
order=1
test_id=test_01


]
}

With jq 1.5, regular expression support has been added 在jq 1.5中,增加了对正则表达式的支持

So assuming property is an array of your test objects (your example is broken and invalid), you could do this to select the objects with names that follow the pattern: 因此,假设property是测试对象的数组(您的示例已损坏且无效),则可以执行以下操作以选择名称遵循该模式的对象:

.property | map(select(.name | test("test[0-9]")))

Then for each of those objects, the value appears to be json strings. 然后,对于每个这些对象,该value似乎都是json字符串。 You would have to parse those out before you could get anything out of those. 您必须先解析出这些内容,然后才能从中获取任何收益。

.property | map(
    select(.name | test("test[0-9]"))
        | .value |= fromjson
        | { name } + .value
    )

This will give you an array: 这将为您提供一个数组:

[
  {
    "name": "test1",
    "test_type": "jsystem",
    "order": 1,
    "test_id": "test_01",
    "physical_setup_id": "prd_01",
    "timeout": "20"
  },
  {
    "name": "test2",
    "test_type": "jsystem",
    "order": 2,
    "test_id": "test_02",
    "physical_setup_id": "prd_02",
    "timeout": "30"
  }
]

Format it to your liking. 将其格式化为您喜欢的格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM