从js中的外部Json对象中删除引号

时间:2016-01-12 10:30:58

标签: javascript json

var obj = '{'include':true,'fn':'1-12'}'

我想读取fn值。如何删除{}?

之外的单引号

4 个答案:

答案 0 :(得分:0)

试试这个

remove double quotes from a String

像这样:

var str = 'remove "foo" delimiting double quotes';
console.log(str.replace(/"([^"]+(?="))"/g, '$1'));
//logs remove foo delimiting quotes
str = 'remove only "foo" delimiting "';//note trailing " at the end
console.log(str.replace(/"([^"]+(?="))"/g, '$1'));
//logs remove only foo delimiting "<-- trailing double quote is not removed

答案 1 :(得分:0)

用双引号'替换单引号",然后使用JSON.parse()方法获取JSON对象。以下作品:

//var obj = '{'include':true,'fn':'1-12'}'; -- This assignment is invalid
var obj = "{'include':true,'fn':'1-12'}"; //Assuming double quotes outside
var obj1 = obj.replace(/'/g, "\""); //Replace single quotes with double quotes
console.log(typeof obj1); // string

var myjsonobj = JSON.parse(obj1); //convert to JSON

//myjsonobj is now a proper JSON object

console.log(myjsonobj); // Object {include: true, fn: "1-12"}
console.log(typeof myjsonobj); // object
console.log(myjsonobj.fn); // 1-12

答案 2 :(得分:-1)

这里适用于你

var regex = /[\']/g;
var obj = "'{'include':true,'fn':'1-12'}'";
obj = obj.replace(regex,"");
console.log(obj);

答案 3 :(得分:-2)

首先,这不是有效的JSON或javascript对象

var obj = '{'include':true,'fn':'1-12'}'

修复您的对象,然后您可以使用eval() 像这样:

var obj = JSON.parse('{"include":true,"fn":"1-12"}');
var fn = eval(obj.fn);