使用jq对JSON进行排序时如何保持UTF-8编码

Rob*_*nig 1 powershell encoding json utf-8 jq

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

\n\n

到目前为止,这工作得很好,但特殊字符(如 \xc3\x9c\xc3\x84\xc3\x96\xc3\xbc\xc3\xa4\xc3\xb6)不会保留在 jq 输出中。

\n\n

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

\n\n
{\n  "sha": "18879fb99367924cd76d402e841155bf73c8afb3",\n  "commit": {\n    "author": {\n    "name": "John Doe \xc3\x9c\xc3\x84\xc3\x96",\n    "email": "john@example.com",\n    "date": "2017-11-23T07:51:22Z"\n    }\n  }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n
{\n  "commit": {\n    "author": {\n      "date": "2017-11-23T07:51:22Z",\n      "email": "john@example.com",\n      "name": "John Doe ???"\n    }\n  },\n  "sha": "18879fb99367924cd76d402e841155bf73c8afb3"\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

如您所见,字符 \xc3\x9c\xc3\x84\xc3\x96 未被识别并保存为 ???。

\n\n

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

\n\n
$json = Get-Content .\\json.txt -Encoding UTF8\n$jsonSorted = $json | .\\jq-win64.exe --sort-keys \'.\'\nSet-Content jsonSorted.txt -Value $jsonSorted -Encoding UTF8\n
Run Code Online (Sandbox Code Playgroud)\n

小智 7

我尝试了这里提到的所有内容,但仍然得到不正确的输出。我必须[System.Console]::OutputEncoding=[System.Text.Encoding]::UTF8在 PowerShell 中进行设置,然后它才能按预期工作。这实际上是我唯一必须做的事情。