Powershell转换为Json是错误的格式 [英] Powershell convert to Json is bad format
问题描述
我正在使用win_shell将powershell输出转换为json格式,以便以后可以对其进行过滤.问题是我的Json格式不正确.
I am using win_shell to convert powershell output to json format, so that i can filter it later. The problem is i am getting bad Json format.
这是代码
- win_shell: |
Get-ChildItem -Path <some_path> |
Where-Object {$_.PSIsContainer} | Sort-Object LastWriteTime -Descending |
Select-Object -First 20 | ConvertTo-Json
register: register_results
- debug:
var: register_results
我得到的标准输出行不干净,无法在json过滤器中使用:
The stdout lines i am getting is not clean to be used in a json filter:
"stderr": "",
"rc": 0,
"stdout_lines": [
"[",
" {",
" \"Name\": \"976\",",
" \"FullName\"\"F:\\\\some\\\\path\\\\to\\\\folder\\\\976\",",
" \"Parent\": {",
" \"Name\": \"first\",",
" \"Parent\": \"All\",",
" \"Exists\": true,",
" \"Root\": \"F:\\\\\",",
" \"Extension\": \"\",",
etc...
当我尝试过滤父母"或姓名"时,这些多余的空格会导致错误.看起来"ConvertToJson"旁边必须有其他参数才能获得输出清理器.
Those extra whitespaces cause errors when i try to filter for example "parent" or "Name". Looks like there must be other parameter beside "ConvertToJson"to get the output cleaner.
反正有这样做吗?
推荐答案
-
ConvertTo-Json
的输出不是 bad JSON,而是 漂亮印刷的 JSON :What
ConvertTo-Json
outputs isn't bad JSON, it is pretty-printed JSON:-
漂亮的JSON使用多行输出和基于空格的缩进来提高可读性.
漂亮打印的JSON是仍然有效的JSON ,但是,任何JSON解析器都可以识别它.
Pretty-printed JSON is still valid JSON, however, and any JSON parser should recognize it.
您可以使用
-Compress
开关 选择退出这种漂亮的印刷方式,以提高效率,但可读性较低表示形式:You can opt out of this pretty-printing with the
-Compress
switch, for a more efficient, but less readable representation:- 您将获得一个单行输出字符串(甚至用于多个输入),并且没有多余的空格.
- You'll get a single-line output string (even for multiple inputs), with no extraneous whitespace.
您显示的输出显示了打印精美的JSON字符串嵌入在另一个JSON字符串 中,作为字符串 property value (因此将嵌入的
"
转换为\"
).The output you're showing shows the pretty-printed JSON string embedded inside another JSON string, as a string property value (hence the escaping of the embedded
"
as\"
).因此,为了处理此类嵌入式JSON,您必须:
Therefore, in order to process such embedded JSON, you must:
- 解析包含 的JSON
- 获取包含 embedded JSON(
< parsedContainingJson> .stdout_lines
)的属性的值 - 然后解析.
- parse the containing JSON
- get the value of the property that contains the embedded JSON (
<parsedContainingJson>.stdout_lines
) - then parse that.
鉴于产生包含JSON的任何内容,都将多行
ConvertTo-Json
输出字符串分解为行数组(如属性名称stdout_lines所建议的那样)
),那么您首先必须将数组元素重新连接为单个字符串,然后再将其作为JSON处理.Given that whatever produces the containing JSON broke the multi-line
ConvertTo-Json
output string into an array of lines (as also suggested by property namestdout_lines
), you'd first have to join the array elements back into a single string before processing them as JSON.如果要避免该步骤,请使用
ConvertTo-Json -Compress
.If you want to avoid that step, use
ConvertTo-Json -Compress
.这篇关于Powershell转换为Json是错误的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
-