Javascript:将字符串转换为对象

时间:2016-02-01 11:13:51

标签: javascript jquery

如何将此字符串转换为对象,以便我可以访问function testCtrl($scope) { $scope.testBtn = function () { if ($scope.testResult == '' || $scope.testResult == null) { $scope.testResult = "Button clicked"; } else { $scope.testResult = ''; } } } 之类的属性?

obj.Name

我尝试过使用{ Name = Mahbubr Rahman, Gender = Male, Birthday = 1 / 5 / 1992 6: 00: 00 AM, Email = mahbubur.rahman@ rms.com, EmployeeType = Manager } JSON.parse(),却一无所获。有什么帮助吗?

eval

3 个答案:

答案 0 :(得分:1)

你可以这样做。使用双引号(“)包装所有属性名称和值,并将=替换为:

var st = '{ Name = Mahbubr Rahman, Gender = Male, Birthday = 1/5/1992 6:00:00 AM, Email = mahbubur.rahman@rms.com, EmployeeType = Manager }';
st = st.replace(/=/g, '":"');
st = st.replace(/{/g, '{"');
st = st.replace(/}/g, '"}');
st = st.replace(/,/g, '","');

var obj = JSON.parse(st);

console.log(obj);

答案 1 :(得分:1)

您可以尝试这样的事情:



var str = '{ Name = Mahbubr Rahman,Gender = Male, Birthday = 1/5/1992 6:00:00 AM, Email = mahbubur.rahman@rms.com, EmployeeType = Manager }';

str = str.replace(/=/g, '\":\"');
str = str.replace(/,/g, "\", \"");
str = str.replace(/{/g, "{\"");
str = str.replace(/}/g, "\"}");

console.log(str);

var obj = JSON.parse(str);

console.log(obj);




答案 2 :(得分:1)

尝试这个

var str = "{ Name = Mahbubr Rahman,Gender = Male, Birthday = 1/5/1992 6:00:00 AM, Email = mahbubur.rahman@rms.com, EmployeeType = Manager }"

var obj = JSON.parse(str.split(/\s*=\s*/).join("\":\"").split(/\s*,\s*/).join("\",\"").split(/{\s*/).join("{\"").split(/\s*}/).join("\"}"));

console.log(obj);