首页 > 解决方案 > 在 CMD 上的 JQ 中使用双引号(windows)

问题描述

Json 文件示例(test1.json):

{
  "entries": [
    {
      "duration": 478,
      "id": "uCPPyitzI",
      "title": "Why | TV",
      "description": null,
      "uploader": null,
      "view_count": null,
      "ie_key": "Youtube",
      "url": "uCPPyitzI",
      "_type": "url_transparent"
    },
    {
      "duration": 245,
      "id": "F9ClW8Dv0",
      "title": "Kejrixxxx | TV",
      "description": null,
      "uploader": null,
      "view_count": null,
      "ie_key": "Youtube",
      "url": "F9ClW8Dv0",
      "_type": "url_transparent"
    },
    {
      "duration": 990,
      "id": "JchBXwZ8o",
      "title": "Battle Of xxxx: | Dr. cccccc | TV",
      "description": null,
      "uploader": null,
      "view_count": null,
      "ie_key": "Youtube",
      "url": "JchBXwZ8o",
      "_type": "url_transparent"
    },
    {
      "duration": 1178,
      "id": "4x9dWcG2c",
      "title": "Dirty Politics | Dr. xxxxx | TV",
      "description": null,
      "uploader": null,
      "view_count": null,
      "ie_key": "Youtube",
      "url": "4x9dWcd2c",
      "_type": "url_transparent"
    }
  ],
  "uploader_id": "xxxx",
  "webpage_url": "https://www.youtube.com/playlist?list=xxx",
  "title": ".aabbcc",
  "extractor": "xxx:xxx",
  "uploader": "xxxxxx",
  "uploader_url": "https://www.youtube.com/channel/xxxx",
  "id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "extractor_key": "xxxxx",
  "webpage_url_basename": "xxxxxx",
  "_type": "playlist"
}

以下命令在 Linux 中运行良好:

猫 test1.json | jq -r '.条目 | 地图(.id +" | "+ .title) | 加入(“\n”)'

根据 jq 文档:

使用 Windows 命令外壳 (cmd.exe) 时,最好在命令行中给出的 jq 程序周围使用双引号(而不是 -f 程序文件选项),但随后 jq 程序中的双引号需要反斜杠转义。

所以我将命令修改为 cmd.exe (Windows 10):

猫 test1.json | jq -r ".[] | map(.id +\" | \" + .title) | join(\" \n \")"

但我不断收到以下错误:

'\" + .title) | join(\"' 未被识别为内部或外部命令,
可运行的程序或批处理文件。

我究竟做错了什么?请帮忙。

标签: jsonwindowscmdjq

解决方案


不幸的是,试图对 Windows 有所帮助的 jq 文档最终有点误导。也许最好提供一个指向综合文档的指针,并建议通过使用 -f 命令行选项来避免令人头疼的问题。

缺少的重要细节之一是插入符号^用作符号的转义字符,例如|. 所以你可以写:

 .entries ^| map(.id +^" ^| ^"+ .title) ^| join(^"\n^")

没有任何周围的引号。

或者——更神秘一点——你可以这样写:

".entries | map(.id +\" ^| \"+ .title) | join(\"\n\")"

正如您可以从上述行中并非所有管道字符都被转义的事实推断出的那样,这种技术并不是那么简单。有关更多详细信息,请参见例如这篇 SO 文章:Escape double quotes in parameter

或者:

https://www.robvanderwoude.com/escapechars.php

有关在线工具,请参阅http://output.jsbin.com/anitaz/11


推荐阅读