Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用shell脚本从html页面上的javascript中获取JSON字符串_Json_Regex_Shell_Sed_Jq_Pup - Fatal编程技术网

使用shell脚本从html页面上的javascript中获取JSON字符串

使用shell脚本从html页面上的javascript中获取JSON字符串,json,regex,shell,sed,jq,pup,Json,Regex,Shell,Sed,Jq,Pup,html页面上的javascript中有有效的json,我想用shell脚本对其进行解析。 首先,我想获得从{到}的整个json字符串,然后我可以用jq解析它 这就是我的html的基本外观: <!DOCTYPE html> <html> <head> <title>foobar</title> </head> <body> <script type="text/javascri

html页面上的javascript中有有效的json,我想用shell脚本对其进行解析。 首先,我想获得从
{
}
的整个json字符串,然后我可以用
jq
解析它

这就是我的html的基本外观:

<!DOCTYPE html>
<html>
  <head>
    <title>foobar</title>

  </head>

  <body>

  <script type="text/javascript" src="resources/script.js" charset="UTF-8"></script>
  <script type="text/javascript" src="resources/resources.js" charset="UTF-8"></script>

    <script type="text/javascript">
    if( foo.foobar.getInstance().isbar() ) 
    {
        foo.bar.Processor.message( {"head":{"url":"anotherfoo;barid=347EDAFA2B136D7825745B0A490DE32"},...});
    }
    else
    {....}
    </script>
  </body>
</html>

福巴
if(foo.foobar.getInstance().isbar())
{
foo.bar.Processor.message({“head”:{“url”:“anotherfoo;barid=347EDAFA2B136D7825745B0A490DE32”},…});
}
其他的
{....}
最后,我想得到位于“barid=…”的ID。 我试着使用
grep foo.bar.Processor.message
,然后使用
sed
cut
,但我认为有更好的方法。 如果你能给我指出正确的方向那就太好了!
谢谢大家!

通常不建议使用unix命令行工具来解析HTML。但如果您知道标记字符串
foo.bar.Processor.message
,则可以使用此
sed+jq
解决方案:

sed -n 's/foo\.bar\.Processor\.message(\([^)]*\).*/\1/p' file.html |
jq -r '.head.url | split(";")[1] | split("=")[1]'
sed -n 's/foo\.bar\.Processor\.message(\([^)]*\).*/\1/p' file.html |
grep -oP ';barid=\K\w+'

如果没有
jq
,您可以使用此
sed+gnu grep
解决方案:

sed -n 's/foo\.bar\.Processor\.message(\([^)]*\).*/\1/p' file.html |
jq -r '.head.url | split(";")[1] | split("=")[1]'
sed -n 's/foo\.bar\.Processor\.message(\([^)]*\).*/\1/p' file.html |
grep -oP ';barid=\K\w+'

一个选项可能是使用,至少用于解析HTML:

< input.html pup 'script:not(:empty) text{}' |
  grep foo.bar.Processor.message | grep -o '{.*}' |
  jq -r '.head.url
         | split(";")[]
         | select(test("barid="))
         | sub("barid=";"")'
当然,还有很多警告。YMMV