转换 JSON 文件时出现“无效的 JSON 原语”错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24453320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"Invalid JSON primitive" error when converting JSON file
提问by user3770612
When trying to convert a JSON file via PowerShell:
尝试通过 PowerShell 转换 JSON 文件时:
$json = Get-Content "C:\folder1\test.txt"
$json | ConvertFrom-Json
write-output $json
I'm getting the following error:
我收到以下错误:
invalid json primitive : [.
(system.argunment.exception)
无效的 json 原语:[.
(system.argunment.exception)
回答by Ansgar Wiechers
I'm going out on a limb here, since you didn't provide your input data or the complete error message, but I guess that your problem is caused by a format mismatch between the output Get-Contentprovides and the input ConvertFrom-Jsonexpects.
由于您没有提供输入数据或完整的错误消息,因此我在这里有点犹豫,但我猜您的问题是由输出Get-Content提供的和输入ConvertFrom-Json预期之间的格式不匹配引起的。
Get-Contentreads the input file into an array of strings, whereas ConvertFrom-Jsonexpects the JSON data in a single string. Also, piping $jsoninto ConvertFrom-Jsondoes not change the value of $json.
Get-Content将输入文件读入字符串数组,而ConvertFrom-Json期望 JSON 数据为单个字符串。此外,管道$json进入ConvertFrom-Json不会改变 的值$json。
Change your code to the following and the error should disapear (provided there is no syntactical error in your input data):
将您的代码更改为以下内容,错误应该会消失(前提是您的输入数据中没有语法错误):
$json = Get-Content 'C:\folder1\test.txt' | Out-String | ConvertFrom-Json
Write-Output $json
回答by itrjll
You should check your JSON input file for characters that are not properly escaped with a "\"
您应该检查 JSON 输入文件中是否有未正确使用“\”转义的字符
I have also seen this issue with an input JSON file that was incorrectly formatted as follows:
我也看到过格式不正确的输入 JSON 文件的这个问题,如下所示:
{
Object1
}
{
Object2
}
Corrected format:
更正的格式:
[{
Object1
},
{
Object2
}]
Once the format was corrected, I had no more issues.
一旦格式得到纠正,我就没有更多的问题了。
回答by uranibaba
You will get this error if your input data starts like this:
如果您的输入数据如下所示,您将收到此错误:
data: [
{
...
},
{
...
}
]
You need to remove data:(and only have [and ]in this example):
您需要删除data:([并且]在本例中只有和):
[
{
...
},
{
...
}
]
回答by bpilling
I was also receiving this error, and upon investigating my json file noticed that some of the JSON was invalid. I was ending the last object in an array with a comma like so:
我也收到了这个错误,在调查我的 json 文件时注意到一些 JSON 无效。我用逗号结束数组中的最后一个对象,如下所示:
[{ ..},]
Removing the comma fixed the issue for myself.
删除逗号为我自己解决了这个问题。
So in short, invalid JSON caused this issue for me.
简而言之,无效的 JSON 给我造成了这个问题。

