gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 14:18:43 28 4
gpt4 key购买 nike

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

例如,如果文件包含:

this
is
a
sample
file

脚本将生成:

"this\r\nis\r\na\r\nsample\r\nfile"

插入 JSON 模板:

"something":"<insertPoint>"

生产:

"something":"this\r\nis\r\na\r\nsample\r\nfile"

我正在使用 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

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

"something":"{
"value": "this\r\nis\r\na\r\nsample\r\nfile"
"PSPath": "C:\\src\\intro.md",
"PSParentPath": "C:\\src",
"PSChildName": "intro.md",
etc...

最终,我尝试通过 JSON 将小型富文本段发送到网页,但希望使用 Markdown 在本地编辑和存储它们。如果这没有意义,并且有更好的发送方式,请也告诉我。

最佳答案

iRon's answer建议不要使用字符串操作在 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
}

问题的根本原因是 Get-ContentNoteProperty 属性的形式用元数据修饰其输出的字符串,并且ConvertTo-Json 目前总是包含这些。

  • 可以在 GitHub issue #7537 中找到允许在调用 Get-Content 时选择退出此装饰的提案。 .
  • 作为补充,GitHub issue #5797建议 ConvertTo-Json 应忽略原始 .NET 类型(例如字符串)的额外属性。

最简单的解决方法使用 .psobject.baseobject 访问底层 .NET 实例,这会绕过 PowerShell 使用的不可见包装对象提供额外的属性:

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

关于json - 使用 Powershell 将文件内容转换为可以使用 JSON 传输的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53571161/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com