繁体   English   中英

将不带引号的 json 字符串解析为 json

[英]Parse the json string without quotes into json

由于键不在引号内,因此以下 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"}]}

我试过了:

  1. JSON.parse - 它不起作用,因为键不在引号内。

  2. eval('('+str+')') -- 由于某种原因没有转换,由于安全性,也很少不情愿这个解决方案。

  3. 手动插入双引号分隔冒号 (:) 但我的值之一,即 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 obj = eval('(' + str + ')');
var json = JSON.stringify(obj);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM