在shell脚本中解析json数组

在shell脚本中解析json数组

本文介绍了在shell脚本中解析json数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从json字符串打印键值。我已经分析了一个简单的json字符串

i need to print key and values from a json string. i allready parse a simple json string

            {
              "Name": "test1",
              "CreateDate": "2016-08-30T10:52:52Z",
              "Id": "testId1",
            }

我的代码像这样

 q1=$(echo $x | grep -Po '"Name":.*?[^\\]",'| perl -pe 's/"Name": //; s/^"//; s/",$//');

 q2=$(echo $x | grep -Po '"Id":.*?[^\\]",'| perl -pe 's/"Id": //; s/^"//; s/",$//');

    echo $q1 "," $q2;

但是这段代码并不适用于像这样的json字符串

But this code is not applicable for json string like this

x='{    "TestNames":
        [{
        "Name": "test1",
        "CreateDate": "2016-08-30T10:52:52Z",
        "Id": "testId1"
         },
         {
        "Name":  "test2",
        "CreateDate": "2016-08-30T10:52:13Z",
        "Id": "testId2"
    }]
}';

我需要像这样打印

test1 , testId1
test2 , testId2

是吗?可能使用grep命令获得像这样的数据?

is it possible to get data like this using grep command?

推荐答案

首先,您的数据不是有效的json,有一个逗号太多:

First, your data is not valid json, there is a comma too much:

{
  "TestNames": [
    {
      "Name": "test1",
      "CreateDate": "2016-08-30T10:52:52Z",
      "Id": "testId1", <--- Remove that!
    },
    {
      "Name": "test2",
      "CreateDate": "2016-08-30T10:52:13Z",
      "Id": "testId2"
    }
  ]
}

已修复您可以使用 jq 在命令行上解析json:

Once you've fixed that you can use jq for parsing json on the command line:

echo "$x" | jq -r '.TestNames[]|"\(.Name) , \(.Id)"'

如果您需要保留输出值。

if you need to keep the output values.

declare -A map1

while read name id ; do
    echo "$name"
    echo "$id"
    map1[$name]=$id

done < <(echo "$x" | jq -r '.TestNames[]|"\(.Name) \(.Id)"')

echo "count : ${#map1[@]}"
echo "in loop: ${map1[$name]}"

这篇关于在shell脚本中解析json数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 21:07