用sed提取json值 [英] Extract json value with sed
问题描述
我有一个json结果,我想提取一个不带双引号的字符串
I have a json result and I would like to extract a string without double quotes
{"value1":5.0,"value2":2.5,"value3":"2019-10-24T15:26:00.000Z","modifier":[]}
使用此正则表达式,我可以正确提取value3(019-10-24T15:26:00.000Z)
With this regex I can extract the value3 (019-10-24T15:26:00.000Z) correctly
sed -e 's/^.*"endTime":"\([^"]*\)".*$/\1/'
如何提取没有双引号的字符串"value2"结果?
How can I extract the "value2" result, a string without double quotes?
我需要处理sed,因此无法安装jq.那是我的问题
推荐答案
只需运行jq
一个命令行JSON处理程序 r
$ json_data='{"value1":5.0,"value2":2.5,"value3":"2019-10-24T15:26:00.000Z","modifier":[]}'
$ jq '.value2' <(echo "$json_data")
2.5
使用键.value2
来访问您感兴趣的值.
with the key .value2
to access the value you are interested in.
此链接总结了为什么您不应该不使用正则表达式解析json的原因 (XML/HTML和其他数据结构也是如此 理论可以无限嵌套)
This link summarize why you should NOT use, regex for parsing json (the same goes for XML/HTML and other data structures that are in theory can be infinitely nested)
用于解析单个键的正则表达式:值Javascript中没有JSON
如果没有jq
可用:
您可以使用以下GNU grep
命令:
you can use the following GNU grep
command:
$ echo '{"value1":5.0,"value2":2.5,"value3":"2019-10-24T15:26:00.000Z","modifier":[]}' | grep -zoP '"value2":\s*\K[^\s,]*(?=\s*,)'
2.5
使用此处详述的正则表达式:
using the regex detailed here:
"value2":\s*\K[^\s,]*(?=\s*,)
演示: https://regex101.com/r/82J6Cb /1/
如果json没有线性化,这甚至可以工作!!!
使用python
也是很直接的,即使不是python3,它也应该默认安装在计算机上
With python
it is also pretty direct and you should have it installed by default on your machine even if it is not python3 it should work
$ cat data.json
{"value1":5.0,"value2":2.5,"value3":"2019-10-24T15:26:00.000Z","modifier":[]}
$ cat extract_value2.py
import json
with open('data.json') as f:
data = json.load(f)
print(data["value2"])
$ python extract_value2.py
2.5
这篇关于用sed提取json值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!