以下json字符串无法转换为json,因为键名没有用引号括起来。
{file:"http://video.test.com/media/myvideo.mp4", image:"/category/dt/filename.png", width:"100%", height:"100%", stretching:"uniform", autostart:true, modes:[{type:"flash", src:"/swf/external/player.swf"}, {type:"html5"}]}
我尝试过:
JSON.parse --- 由于键不在引号内,无法解析。
eval('('+str+')') --- 不知道为什么无法转换,同时也因为安全原因有些犹豫采用此解决方案。
手动插入双引号来分隔冒号(:),但我的一个值(即一个URL)中也有一个冒号,如下解决方案所示:正则表达式在JavaScript中添加双引号来包装值和键
为什么很难将这个字符串转换成json,怎样才能转换它?
var s = '{file:"http://video.test.com/media/myvideo.mp4", image:"/category/dt/filename.png", width:"100%", height:"100%", stretching:"uniform", autostart:true, modes:[{type:"flash", src:"/swf/external/player.swf"}, {type:"html5"}]}';
console.log(eval('(' + s + ')'));
var result = eval('('+str+')')
应该可以正常工作。 - Jaromanda X[...]他们无法立即支持发送json[...]
,但这是否意味着你对他们如何格式化该字符串没有任何影响?因为最简单的方法是让他们将该字符串以正确的JSON格式存储在HTML文档中。 - t.niese