I am running into a parsing problem when loading JSON files that seem to have the TAB character in them.

当我转到http://jsonlint.com/时,我输入带有制表符的零件:

{
    "My_String": "Foo bar.  Bar foo."
}

The validator complains with:

Parse error on line 2:
{    "My_String": "Foo bar. Bar foo."
------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['

这实际上是有问题的JSON文本的复制/粘贴.

I have tried loading this file with json and simplejson without success. How can I load this properly? Should I just pre-process the file and replace TAB by \t or by a space? Or is there anything that I am missing here?

Update:

以下是simplejson中的一个有问题的例子:

foo = '{"My_string": "Foo bar.\t Bar foo."}'
simplejson.loads(foo)

JSONDecodeError: Invalid control character '\t' at: line 1 column 24 (char 23)

推荐答案

JSON standard:

允许在任何标记之前或之后使用无关紧要的空格.这个 空格字符包括:字符制表符(U+0009)、换行符 (U+000A)、回车(U+000D)和空格(U+0020).空格是 在任何标记内都不允许,除非允许在 弦.

这意味着JSON字符串中不允许使用文本制表符.你需要以\t (in a .json-file)的形式逃离它:

{"My_string": "Foo bar.\t Bar foo."}

此外,如果在Python字符串文本中提供json文本,则需要双重转义该选项卡:

foo = '{"My_string": "Foo bar.\\t Bar foo."}' # in a Python source

或者使用Python原始字符串文字:

foo = r'{"My_string": "Foo bar.\t Bar foo."}' # in a Python source

Json相关问答推荐

筛选JSON数组以使用Jolt仅保留具有最新日期/时间的条目

Bash和echo命令出现意外结果

如何将加权边列表导出到JSON树?

Vega Lite中的图例对齐

Python将Pandas转换为嵌套的JSON

写入JSON文件的流

组合不同属性的Jolt Spec

VBA json按特定属性名称提取所有数据

如何从一个700MB的json文件中列出PowerShell中的所有密钥?

jq - 仅在键值对存在的地方打印值

JOLT 在 struct 体中间添加一个 JSON 字段

Jolt - 在同一级别添加时组合值的问题

谷歌浏览器不允许我放置断点

在 Http Header 中使用 Json 字符串

通过 RestAssured 中的 JsonPath 访问匿名数组的元素

有必要清理 JSON 吗?

Select 什么数据类型json或者jsonb或者text

从 VS 2017 Azure Function 开发中的 local.settings.json 读取值

为什么 JavaScript 的 eval 需要括号来判断 JSON 数据?

如何在 React js 中解析本地 JSON 文件?