【问题标题】:How to keep UTF-8 encoding when sorting JSON with jq使用 jq 对 JSON 进行排序时如何保持 UTF-8 编码
【发布时间】:2018-05-11 15:46:27
【问题描述】:

我在 Windows PowerShell 上使用 jq 1.5 按字母顺序对 JSON 文件的字段进行排序。

到目前为止,这工作得很好,但特殊字符(如 ÜÄÖüäö)不会保留在 jq 输出中。

原始文件以UTF-8编码保存:

{
  "sha": "18879fb99367924cd76d402e841155bf73c8afb3",
  "commit": {
    "author": {
    "name": "John Doe ÜÄÖ",
    "email": "john@example.com",
    "date": "2017-11-23T07:51:22Z"
    }
  }
}

这是保存为 UTF-8 的 jq 输出:

{
  "commit": {
    "author": {
      "date": "2017-11-23T07:51:22Z",
      "email": "john@example.com",
      "name": "John Doe ???"
    }
  },
  "sha": "18879fb99367924cd76d402e841155bf73c8afb3"
}

如您所见,字符 ÜÄÖ 无法识别并保存为 ???。

这就是我在 PowerShell 中使用 jq 的方式:

$json = Get-Content .\json.txt -Encoding UTF8
$jsonSorted = $json | .\jq-win64.exe --sort-keys '.'
Set-Content jsonSorted.txt -Value $jsonSorted -Encoding UTF8

【问题讨论】:

  • 正如答案中所建议的那样,在 PowerShell 中更改代码页 chcp 65001 已解决此问题。但更重要的是,我还必须更改对 jq 可执行文件的调用:$jsonSorted = .\jq-win64.exe --sort-keys '.' json.txt 所以不再需要使用 Get-Content cmdlet。

标签: json powershell encoding utf-8 jq


【解决方案1】:

您没有提及您使用的是哪个版本的 jq,但我强烈怀疑您遇到了一个已修复的错误。我相信最近的 UTF-8 错误是由 https://github.com/stedolan/jq/pull/1317 一月下旬。不幸的是,这意味着要进行修复,您很可能需要比 1.5 更新的 jq 版本。

由于您使用的是 Windows,我建议您查看https://github.com/stedolan/jq/wiki/Installation#windows-using-appveyor

代码页

也许更改代码页会有所帮助?在命令提示符下,首先运行chcp 以确定当前代码页;如果还不是 65001,请运行 chcp 65001

另见https://superuser.com/questions/237081/whats-the-code-page-of-utf-8

在 Mac 上验证

$ file john-doe.json
john-doe.json: UTF-8 Unicode text

$ cat  john-doe.json
"John Doe ÜÄÖ"

$ jq --version
jq-1.5

$ jq . john-doe.json
"John Doe ÜÄÖ"

$ jqMaster --version
jq-1.5rc2-250-g239278f

$ jqMaster . john-doe.json
"John Doe ÜÄÖ"

【讨论】:

  • 我使用的是 1.5 版。我会检查 Appveyor 看看它是否能解决我的问题。
  • 我从here 下载了最新版本,但我仍然遇到同样的问题。 .\jq.exe --version jq-1.5rc2-250-g239278f
  • 请查看更新。至少你现在拥有最好的 jq :-)
  • 感谢您的帮助。版本本身不是问题。我认为 Get-Content cmdlet 以某种方式在这里产生了问题。将文件输入直接设置为 jq,就像您在验证中所做的那样,我的机器上的两个版本也都可以正常工作。
  • 奇怪的是,当我将 jq 的输出保存在一个变量中时,输出看起来像这样:"name": "John Doe ├£├ä├û"
猜你喜欢
  • 2021-07-26
  • 2010-11-15
  • 2017-08-29
  • 2020-07-05
  • 2018-10-11
  • 2018-06-23
  • 2018-08-19
  • 2016-11-10
  • 1970-01-01
相关资源
最近更新 更多