使用jquery从json字符串中的键中删除引号

时间:2010-09-06 12:05:31

标签: jquery json key

将此视为我的json字符串,

{"Table" : [{"userid" : "11","name" : "KumarP","designation" : "Business Head",
"phone" : "9789234793","email" : "surfingkumar@gmail.com","role" : "Admin",
   "empId" : "EI003","reportingto" : "KumarP"}]}

我想让我的字符串像这样,

{Table:[{ userid: "11", name: "KumarP", designation: "Business Head", 
    phone: "9789234793", email:"surfingkumar@gmail.com", role : "Admin",
       empId : "EI003",reportingto : "KumarP"}]}

我这样做是为了与jlinq一起使用..

2 个答案:

答案 0 :(得分:18)

使用正则表达式:

var a='{"Table" : [{"userid" : "11","name" : "KumarP","designation" : "Business Head","phone" : "9789234793","email" : "surfingkumar@gmail.com","role" : "Admin",    "empId" : "EI003","reportingto" : "KumarP"}]}';
a=a.replace(/"(\w+)"\s*:/g, '$1:');
alert(a);

该字符串将成为您的第二个代码块:

{Table: [{userid: "11",name: "KumarP",designation: "Business Head",phone: "9789234793",email: "surfingkumar@gmail.com",role: "Admin",    empId: "EI003",reportingto: "KumarP"}]}

但如果标签是保留字,那么这不会导致问题吗?

答案 1 :(得分:7)

如果你拥有的实际上是一个JSON字符串,如:

var obj = '{"Table" : [{"userid" : "11","name" :"KumarP","designation" : "Business Head",\
"phone" : "9789234793","email" : "surfingkumar@gmail.com","role" : "Admin",\
"empId" : "EI003","reportingto" : "KumarP"}]}';

然后你可以用$.parseJSON()解析它,如:

var result = $.parseJSON( obj );

这会将您的JSON字符串转换为javascript对象/数组。