如何将字符串解析为对象?

时间:2018-03-16 09:51:01

标签: javascript parsing

背景

我有一个包含javascript对象的字符串。此字符串不是JSON字符串化的(只有一部分是)。

我需要将此字符串转换为对象,以便我可以使用它。

以下是此类字符串的示例:

`{method: 'POST', url: '/iot/pipe/', query: {}, body: { d: '{"n": "861359031087669", "b": 100, "v": "02.37", "t": 1, "d":[[1515070895,413973366,21717600,110,1,0],[1515070897,413975033,21719083,102,1,0]]}' }, headers: { host: 'node_session_iot', connection: 'close', 'content-length': '1219', accept: '*/*', 'user-agent': 'QUECTEL_MODULE', 'content-type': 'application/x-www-form-urlencoded' } }`

JSON.parse

字符串不是json字符串化,因此解析将失败。

eval

eval是邪恶的。永远不要使用它。

解决方案?

我发现它非常令人沮丧。我的对象就在我面前,我无法做到这一点。 我还有什么其他选择将此字符串转换为对象?

2 个答案:

答案 0 :(得分:3)

嗯,我不会说这是一个完美的解决方案,它是非常具体的例子,但想法是将字符串逐步转换为JSON字符串

希望它有效

//take in quotation
y = x.replace(/(\w+)(\s*:)+/g,"\"\$1\"$2");
//convert single quotation into "
y = y.replace(/\'/g,"\"" );
// remove " from object literals
y = y.replace(/\"\s*{/g,"{" );
y = y.replace(/}\"\s*/g,"}" );
yOjb = JSON.parse(y);

答案 1 :(得分:0)

您的请求正文采用正确的JSON格式。 因此,使用正则表达式或字符串函数从给定字符串中获取请求体,并使用JSON.Parse方法获取对象。

在这种情况下,您的请求正文是

{"n": "861359031087669", "b": 100, "v": "02.37", "t": 1, "d":[[1515070895,413973366,21717600,110,1,0],[1515070897,413975033,21719083,102,1,0]]}

请参阅下面的JSON.Parse函数快照。 enter image description here