转换JSON文件时出现“无效的JSON原语”错误

时间:2014-06-27 13:41:15

标签: json powershell

尝试通过PowerShell转换JSON文件时:

$json = Get-Content "C:\folder1\test.txt"

$json | ConvertFrom-Json 

write-output $json

我收到以下错误:

  

无效的json原语:[。
  (system.argunment.exception)

4 个答案:

答案 0 :(得分:14)

我出去了,因为你没有提供输入数据或完整的错误信息,但我猜你的问题是由输出{{1}之间的格式不匹配引起的提供和输入Get-Content期望。

ConvertFrom-Json将输入文件读入字符串数组,而Get-Content期望单个字符串中的JSON数据。此外,将ConvertFrom-Json加入$json并不会更改ConvertFrom-Json的值。

将您的代码更改为以下内容并且错误应该消失(假设您的输入数据中没有语法错误):

$json

答案 1 :(得分:10)

您应该检查您的JSON输入文件中是否有未通过“\”

正确转义的字符

我也看到了这个问题,输入的JSON文件格式不正确如下:

{
    Object1
}
{
    Object2
}

更正后的格式:

[{
     Object1
 },
 { 
     Object2
 }]

一旦格式得到纠正,我就不再有问题了。

答案 2 :(得分:0)

如果您的输入数据是这样开始的,则会出现此错误:

data: [
  {
    ...
  },
  {
    ...
  }
]

您需要删除data:(在此示例中只有[]

[
  {
    ...
  },
  {
    ...
  }
]

答案 3 :(得分:0)

我也收到此错误,并且在调查我的json文件时发现某些JSON无效。我用逗号结束数组中的最后一个对象,如下所示:

import re
from docx import Document
from docx.shared import Pt
from docx.shared import Inches
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT

alignment_dict={'justify':WD_PARAGRAPH_ALIGNMENT.JUSTIFY,
                'center':WD_PARAGRAPH_ALIGNMENT.CENTER,
                'right':WD_PARAGRAPH_ALIGNMENT.RIGHT,
                'left':WD_PARAGRAPH_ALIGNMENT.LEFT}
def get_docx_align(doc,align='justify'):
    for para in doc.paragraphs:
        inline=para.runs
        for i in range(len(inline)):
            inline[i].text=re.sub('[\t]+','',inline[i].text)
            inline[i].text=re.sub('[\n]+','\n',inline[i].text)
            inline[i].text=re.sub('[" "]+',' ',inline[i].text)
            #p=para._element
            #p.getparent().remove(p)
            #p._p=p._element=None
        paragraph=para
        paragraph_format=paragraph.paragraph_format
        paragraph_format.alignment=alignment_dict.get(align.lower())
doc=Document('Word_in.docx')
get_docx_align(doc,align='justify')
doc.save('Word_out.docx')

删除逗号可以自己解决此问题。

简而言之,无效的JSON对我造成了此问题。