我试图将字符串解析为JSON,我收到一个意外的令牌错误.
我正在使用http://json.parser.online.fr/检查有效性,它没有出现任何解析错误,但仍然说eval由于意外令牌而失败.如果您将JSON从下面粘贴到该网站,您可以看到它发现错误,但没有指定导致它的令牌.
下面是我要解析的内容.
{
"Polish": {
"Rent": [
{
"english": "a",
"audioUrl": "b",
"alternate": "c"
},
{
"english": "d",
"audioUrl": "e",
"alternate": "f"
}
]
}
}
Run Code Online (Sandbox Code Playgroud)
我错过了一些明显的东西吗
编辑
在:和"租"键后面有一个不可打印的字符.
我在解析尝试之前对字符串执行了一些replace()调用,这可能会产生问题.
在解析特定行之前
"Rent":"[
Run Code Online (Sandbox Code Playgroud)
我想删除:和[sybmols之间的双引号.
所以我正在使用:
var reg = new RegExp('":"', 'g');
var newStr = originalStr.replace(reg, '":');
Run Code Online (Sandbox Code Playgroud)
我不知道上面为什么会导致不可打印的角色.
EDIT2
我做了一个快速检查删除上面的replace()调用粘贴到验证器,手动删除我使用replace()的双引号,并且不可读的字符仍然存在.因此错误出现在原始字符串中.所以更多的代码:|
该字符串从ajax调用返回到驻留在服务器上的php脚本.PHP脚本正在读取服务器上的目录并填充嵌套的关联数组以生成发送回JS端的字符串,JS端编辑并解析它(如上所示).
在目录中是JSON文件,我将这些内容插入到这个嵌套的数组结构中以完成JSON层次结构.
不可读的角色是
ef bb bf
我用Google搜索并发现是表示文件内容的字符串的字节顺序标记.
所以继承PHP代码读取目录和JSON文件创建嵌套数组结构为JSON_encode()d并发送回JS
if ($langHandle = opendir($langDir)) {
while (false !== ($langEntry = readdir($langHandle))) {
$currentLangDir = $langDir . "/" . $langEntry;
if (is_dir($currentLangDir) && $langEntry != '.' && $langEntry != '..') {
$currentLang = array();
if ($currentLangHandle = opendir($currentLangDir)) {
while (false !== ($catEntry = readdir($currentLangHandle))) {
$currentCatFile = $currentLangDir . "/" . $catEntry;
if(is_file($currentCatFile) && $catEntry != '.' && $catEntry != '..') {
$currentCat = file_get_contents($currentCatFile);
$currentLang[removeFileExtension($catEntry)] = $currentCat;
}
}
}
$langArray[$langEntry] = $currentLang;
}
}
Run Code Online (Sandbox Code Playgroud)
我该怎么做才能修复这些不需要的字符,快速搜索删除BOM字符表示这是一件坏事.
您可能有一个不可打印的字符,但未显示在您在问题中粘贴的内容中.我将您的文本复制并粘贴到您提供的链接的在线解析器中,并且干净地解析.
尝试将原始文本复制并粘贴到此在线十六进制转储网站中,并与从上面的SO问题复制和粘贴时获得的内容进行比较...如果它们不同,那么您将了解伪造字符的位置.
这是我得到的输出的屏幕截图,它干净地解析.