简体   繁体   English

将 jq 输出分配给 bash 数组

[英]Assign jq output to bash array

I have a problem to assign value to bash array correctly which was parsed by jq .我在为 bash 数组正确分配值时遇到问题,该数组由jq解析。 I have a JSON output from curl :我有curl的 JSON 输出:

{
  "id": 6442,
  "name": "Execute Workflow",
  "description": "Plan: data",
  "status": "In Queue",
  "start_date": 0,
  "end_date": 0,
  "job_type": "Execute Workflow",
  "created_by_name": null,
  "creation_date": 1580762385615,
  "creation_date_str": "02/03/2020 09:39:45 PM",
  "last_updated_date": 1580762385615,
  "last_updated_date_str": "02/03/2020 09:39:45 PM",
  "last_updated_by_name": null,
  "schedule_on": 0,
  "paused_at_step": 0,
  "percent_complete": 0,
  "job_action_type": null,
  "child_job_id": -1
}

I want to save two key values .id and .status into bash array.我想将两个键值.id.status保存到 bash 数组中。

I am doing it this way:我是这样做的:

array=( $(echo '{ "id": 6442, "name": "Execute Workflow", "description": "Plan: data", "status": "In Queue", "start_date": 0, "end_date": 0, "job_type": "Execute Workflow", "created_by_name": null, "creation_date": 1580762385615, "creation_date_str": "02/03/2020 09:39:45 PM", "last_updated_date": 1580762385615, "last_updated_date_str": "02/03/2020 09:39:45 PM", "last_updated_by_name": null, "schedule_on": 0, "paused_at_step": 0, "percent_complete": 0, "job_action_type": null, "child_job_id": -1}' | jq '.id, .status') ) 

All seems OK until I try to get second element of that array: echo ${array[1]} and I get "In not "In Queue" .一切似乎都很好,直到我尝试获取该数组的第二个元素: echo ${array[1]}并且我得到"In not "In Queue"

My array is 3 elements long echo ${#array[@]} returns 3 but I want it to be 2 elements long.我的数组长度为 3 个元素echo ${#array[@]}返回3但我希望它的长度为 2 个元素。 Can someone help me please?有人能帮助我吗?

My next steps in bash script is to assign job_status="=${array[1]}" and I want to get variable job_status="In Queue" .我在 bash 脚本中的下一步是分配job_status="=${array[1]}"并且我想获得变量job_status="In Queue"

yes, when you assign to an array, bash has to escape all its special characters and then split the arguments with the default separator, which is space.是的,当您分配给数组时,bash 必须转义其所有特殊字符,然后使用默认分隔符(空格)拆分参数。 There's no matter of quoting of arguments or spaces per se in the source JSON that would help here.在源 JSON 中引用参数或空格本身不会有帮助。

Thus, to work-around that you'd need to set IFS to the delimiter which is unique enough for your JSON data - for the sake of the example, let it be comma (assuming your JSON is in curl.json for brevity):因此,要解决这个问题,您需要将IFS设置为对您的 JSON 数据足够独特的分隔符 - 就示例而言,将其设为逗号(假设您的 JSON 在curl.json为简洁起见):

bash $ ifs="$IFS"; IFS=','; array=($(<curl.json jq -r '[.id, .status] | @csv')); IFS="$ifs"
bash $ echo ${#array[@]}
2
bash $ echo ${array[1]}
"In Queue"
bash $ 

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

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