在JavaScript中将字符串转换为对象 [英] Turning a string into an object in JavaScript

查看:96
本文介绍了在JavaScript中将字符串转换为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用字符串创建一个不是典型JSON字符串的对象。

I am trying to create an object out of string which is not a typical JSON string.

以下是示例:

 var ObjectInString = "{x:62.43993,y:293.64093}"; //string i want to turn into an object
var ObjectWhichWorks = {x:62.43993,y:293.64093};

console.log(ObjectInString);
console.log(ObjectWhichWorks);

推荐答案

假设您的密钥总是 x y ,通过在这些键周围添加双引号将字符串转换为有效的JSON字符串。然后,您可以使用 JSON.parse()获取所需对象:

Assuming your keys are always x and y, convert the string to a valid JSON string by adding double quotes around those keys. You can then use JSON.parse() to get the desired object:

var o = '{x:62.43993,y:293.64093}';

console.log(JSON.parse(o.replace('x', '"x"').replace('y', '"y"')));

这篇关于在JavaScript中将字符串转换为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆