【发布时间】:2011-01-25 12:05:52
【问题描述】:
我将此 JSON 对象存储在纯文本文件中:
{
"MySQL": {
"Server": "(server)",
"Username": "(user)",
"Password": "(pwd)",
"DatabaseName": "(dbname)"
},
"Ftp": {
"Server": "(server)",
"Username": "(user)",
"Password": "(pwd)",
"RootFolder": "(rf)"
},
"BasePath": "../../bin/",
"NotesAppPath": "notas",
"SearchAppPath": "buscar",
"BaseUrl": "http:\/\/montemaiztusitio.com.ar",
"InitialExtensions": [
"nem.mysqlhandler",
"nem.string",
"nem.colour",
"nem.filesystem",
"nem.rss",
"nem.date",
"nem.template",
"nem.media",
"nem.measuring",
"nem.weather",
"nem.currency"
],
"MediaPath": "media",
"MediaGalleriesTable": "journal_media_galleries",
"MediaTable": "journal_media",
"Journal": {
"AllowedAdFileFormats": [
"flv:1",
"jpg:2",
"gif:3",
"png:4",
"swf:5"
],
"AdColumnId": "3",
"RSSLinkFormat": "%DOMAIN%\/notas\/%YEAR%-%MONTH%-%DAY%\/%TITLE%/",
"FrontendLayout": "Flat",
"AdPath": "ad",
"SiteTitle": "Monte Maíz: Tu Sitio",
"GlobalSiteDescription": "Periódico local de Monte Maíz.",
"MoreInfoAt": "Más información aquí, en el Periódico local de Monte Maíz.",
"TemplatePath": "templates",
"WeatherSource": "accuweather:SAM|AR|AR005|MONTE MAIZ",
"WeatherMeasureType": "1",
"CurrencySource": "cotizacion-monedas:Dolar|Euro|Real",
"TimesSingular": "vez",
"TimesPlural": "veces"
}
}
当我尝试使用 json_decode() 对其进行解码时,它返回 NULL。为什么?
该文件是可读的(我尝试回显file_get_contents(),它工作正常)。
我已经针对 http://jsonlint.com/ 测试了 JSON,它完全有效。
这里有什么问题?
更新(对我 2010 年问题的有效回复)
在谷歌上寻找答案,我回到了 SO:json_decode returns NULL after webservice call。我的 JSON 文件具有 UTF BOM 序列(一些不应该存在的二进制字符),因此破坏了 JSON 结构。去十六进制编辑器,擦除字节。一切恢复正常。 为什么会这样? 因为我使用 Microsoft Windows 的记事本编辑了文件。糟糕的想法!
【问题讨论】:
-
使用 PHP 5.2.9;因此,我不能使用
json_last_error()。 -
另请注意,文件中间的其他无效字符可能会发生这种情况。我刚刚让 json_decode() 返回 null,因为字符串包含其中一个特殊的破折号,可能是从 MS Word 粘贴的,然后可能是错误编码的。要识别潜在的问题字符,请打开 JSON 文件(我在 Notepad++ 中使用),更改编码(无需转换),然后另存为副本。然后比较这两个文件(我使用了 WinMerge)。
-
(Windows 记事本问题)请参考这个问题,我也分享了这个问题并修复了它:stackoverflow.com/questions/10290849/…
-
对我来说,这没什么特别的,只是对象元素末尾的一个额外的逗号。带走:任何使您的 JSON 不一致的东西都会引发错误。额外提示:不要相信 jsonviewer.stack.hu 使用类似 jsonlint 的东西