[英]Javascript: Convert string to object
How can i convert this string into object so that i can access it's property like obj.Name
? 如何将此字符串转换为对象,以便我可以访问它的属性,如
obj.Name
?
{
Name = Mahbubr Rahman,
Gender = Male,
Birthday = 1 / 5 / 1992 6: 00: 00 AM,
Email = mahbubur.rahman@ rms.com,
EmployeeType = Manager
}
I have tried with JSON.parse()
and eval
but getting nothing. 我已经尝试过
JSON.parse()
和eval
但什么都没得到。 Any help ? 有帮助吗?
var obj = JSON.parse(
JSON.stringify('{ Name = Mahbubr Rahman,Gender = Male, Birthday = 1/5/1992 6:00:00 AM, Email = mahbubur.rahman@rms.com, EmployeeType = Manager }'.replace(/=/g, ':'))
);
You can do it like following. 你可以像下面这样做。 Wrap all property name and value with double quotes (") and replace
=
with :
. 用双引号(“)和replace
=
with :
包装所有属性名称和值。
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);
You can try something like this: 你可以尝试这样的事情:
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);
try this one as well 试试这个
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.