简体   繁体   English

如何使用jq提取json值子字符串

[英]How to extract a json value substring with jq

I have this json: 我有这个json:

{"temperature":"21", "humidity":"12.3", "message":"Today ID 342 is running"}

I want to use jq to obtain this json: 我想使用jq获取此json:

{"temp":"21", "hum":"12.3", "id":"342"}

As you can see, what i want to do is extract the ID number 342 and put it in the new json with a different key name. 如您所见,我要提取的是ID号342,并将其放入具有不同键名的新json中。 I think i should use a regex but i don't know how to insert it in jq syntax. 我想我应该使用正则表达式,但我不知道如何在jq语法中插入它。

I can create another json using the basic command: 我可以使用基本命令创建另一个json:

cat old.json | jq '{temp:.temperature,hum:.humidity, id:.message}' > new.json

I know i can select substring using square brackets, but i don't want to use them because they don't take into account strings with different lengths and structure. 我知道我可以使用方括号选择子字符串,但是我不想使用它们,因为它们没有考虑具有不同长度和结构的字符串。 I want to use a regex because i know that the ID number comes lways after the "ID" part. 我想使用正则表达式,因为我知道ID号始终在“ ID”部分之后。

You're right that a regex is the way to go here. 您说对了,正则表达式是解决问题的方法。 Fortunately, the jq manual has a large section on using them. 幸运的是, jq手册在使用它们方面有很大一部分。

jq '
{
  temp: .temperature,
  hum: .humidity,
  id: (.message | capture("ID (?<id>[[:digit:]]+)").id)
}' <old.json >new.json

You can see this running with your sample data at https://jqplay.org/s/k-ZylbOC6W 您可以在https://jqplay.org/s/k-ZylbOC​​6W上看到示例数据的运行

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

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