将 Xidel 模式匹配的输出转换为 Json 个对象

Convert Output of Xidel Pattern Match into Json Objects

想知道我是否可以使用文件中的 Xidel 模式将 html 列表转换为 json 对象的数组。

给出这个例子HTML:

<div class="watch-sidebar-body">
  <ul id="watch-related" class="video-list">
    <li class="video-list-item">
      <div class="content-wrapper">
        <a href="/watch?v=XPt3uMaqG7c">
          <span class="title">
            10 Best Super Bowl 2018 Commercials
          </span>
          <span class="accessible-description">
            - Duration: 11:07.
          </span>
          <span class="stat attribution"><span class="">Dalibor Truhlar</span></span>
          <span class="stat view-count">546,346 views</span>
        </a>
      </div>
    </li>
    <li class="video-list-item">
    ...

通过使用文件中的此模式:

<ul id="watch-related" class="video-list">
<t:loop>
<li>
    <a>
      <span class="title">{$title}</span>
      <span class="accessible-description">{$duration := extract(., "[0-9]+:[0-9]+")}</span>
      <span>
        <span>{$author}</span>
      </span>
      <span class="view-count">{$views := extract(., "[0-9,]+")}</span>
      {url := @href}
    </a>
</li>
</t:loop>
</ul>

我想制作以下内容json:

[{ "title" : "10 Best Super Bowl 2018 Commercials"
 , "duration" : "11:07"
 , "author" : "Dalibor Truhlar"
 , "views" : "546,346"
 , "url" : "/watch?v=XPt3uMaqG7c"
 }
,{ "title" : "Funny Commercial Compilation"
 , "duration" : "9:33"
 , "author" : "Gaming Coyote"
 , "views" : "9,449,290"
 , "url" : "/watch?v=BTka0cgf99c"
 }
...

模式与 HTML 正确匹配并提取数据,但我无法获得上面说明的 json 输出。

当我运行命令

curl -s https://www.youtube.com/watch\?v\=HE9nLWFZ6ac | xidel  - --silent --extract-file=yt.xq

我只是在标准输出上获取所有变量的转储:

title := 10 Best Super Bowl 2018 Commercials
duration := 11:07
author := Dalibor Truhlar
views := 548,710
url := /watch?v=XPt3uMaqG7c
title := Funny Commercial Compilation
duration := 9:33
author := Gaming Coyote
views := 9,451,516
url := /watch?v=BTka0cgf99c

但是我如何从这个转到 json 对象数组?

--output-format=json-wrapped 没有帮助,因为它将每个变量转换成它自己的数组,而不是将它们压缩到对象中。

我知道可以在命令行上使用 xpath 表达式创建所需的 json 输出,但我特别感兴趣的是学习如何从文件中存储的模式中获取该输出。

您可以在模式中创建显式对象:

<ul id="watch-related" class="video-list">
<t:loop>
<li>
    <a>

      {$out := {}}

      <span class="title">{$out.title}</span>
      <span class="accessible-description">{$out.duration := extract(., "[0-9]+:[0-9]+")}</span>
      <span>
        <span>{$out.author}</span>
      </span>
      <span class="view-count">{$out.views := extract(., "[0-9,]+")}</span>
      {$out.url := @href}
    </a>
</li>
</t:loop>
</ul>

并用 | xidel - --silent --dot-notation=on --extract-file=yt.xq

调用它