使用Powershell将文件的内容转换为可以使用JSON传输的字符串

Tho*_*son 3 powershell json

如何将文本文件的内容转换为字符串,然后将此字符串插入JSON文件?

例如,如果文件包含:

this
is
a
sample
file
Run Code Online (Sandbox Code Playgroud)

该脚本将生成:

"this\r\nis\r\na\r\nsample\r\nfile"
Run Code Online (Sandbox Code Playgroud)

要插入JSON模板:

"something":"<insertPoint>"
Run Code Online (Sandbox Code Playgroud)

生产:

"something":"this\r\nis\r\na\r\nsample\r\nfile"
Run Code Online (Sandbox Code Playgroud)

我正在使用Powershell 5并设法加载文件,生成一些JSON并通过运行来插入它:

# get contents and convert to JSON
$contentToInsert = Get-Content $sourceFilePath -raw | ConvertTo-Json
# write in output file
(Get-Content $outputFile -Raw).replace('<insertPoint>', $contentToInsert) | Set-Content $outputFile
Run Code Online (Sandbox Code Playgroud)

但是,还添加了许多其他不需要的字段.

"something":"{
  "value":  "this\r\nis\r\na\r\nsample\r\nfile"
  "PSPath":  "C:\\src\\intro.md",
  "PSParentPath":  "C:\\src",
  "PSChildName":  "intro.md",
    etc...
Run Code Online (Sandbox Code Playgroud)

最后,我正在尝试通过JSON将小型富文本段发送到网页,但希望使用Markdown在本地编辑和存储它们.如果这没有意义,并且有更好的方式发送这些,那么请让我知道.

mkl*_*nt0 6

iRon的回答有助于建议不使用字符串操作在PowerShell中创建JSON,而是使用哈希表(或自定义对象)来构造数据,然后将其转换为JSON.

但是,仅凭这一点不能解决您的问题:

PS> @{ something = Get-Content -Raw $sourceFilePath } | ConvertTo-Json
{
  "something": {
    "value": "this\nis\na\nsample\nfile\n",
    "PSPath": "/Users/mklement/Desktop/pg/lines.txt",
    # ... !! unwanted properties are still there
}
Run Code Online (Sandbox Code Playgroud)

问题的根本原因是Get-ContentNoteProperty属性形式的元数据装饰它输出的字符串,并且 ConvertTo-Json当前总是包括这些.

  • Get-Content可以在此GitHub问题中找到允许在呼叫时选择退出此装饰的建议.
  • 补充一点,这个GitHub问题表明ConvertTo-Json应该忽略原始.NET类型(如字符串)的额外属性.

最简单的解决方法访问底层的.NET实例.psobject.baseobject,绕过PowerShell用来提供额外属性的隐形包装器对象:

PS> @{ something = (Get-Content -Raw $sourceFilePath).psobject.baseobject } |
      ConvertTo-Json
{
  "something": "this\nis\na\nsample\nfile\n"
}
Run Code Online (Sandbox Code Playgroud)