字符串到JS中的对象

我有一个字符串as

string = "firstName:name1, lastName:last1";

现在我需要一个对象obj这样

obj = {firstName:name1, lastName:last1}

我如何在JS中做到这一点?

650229 次浏览

你的字符串看起来像一个没有花括号的JSON字符串。

这应该工作,然后:

obj = eval('({' + str + '})');

警告:这引入了重大的安全漏洞,例如XSS与不受信任的数据(由应用程序的用户输入的数据)。

如果我没理解错的话:

var properties = string.split(', ');
var obj = {};
properties.forEach(function(property) {
var tup = property.split(':');
obj[tup[0]] = tup[1];
});

我假设属性名在冒号的左边,它所取的字符串值在右边。

请注意,Array.forEach是JavaScript 1.6——你可能想要使用一个工具包来获得最大的兼容性。

这个简单的方法…

var string = "{firstName:'name1', lastName:'last1'}";
eval('var obj='+string);
alert(obj.firstName);

输出

name1

如果你正在使用JQuery:

var obj = jQuery.parseJSON('{"path":"/img/filename.jpg"}');
console.log(obj.path); // will print /img/filename.jpg

记住:eval是邪恶的!: D

实际上,最好的解决方案是使用JSON:

文档< a href = " https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse " > < / >

JSON.parse(text[, reviver]);

例子:

1)

var myobj = JSON.parse('{ "hello":"world" }');
alert(myobj.hello); // 'world'

2)

var myobj = JSON.parse(JSON.stringify({
hello: "world"
});
alert(myobj.hello); // 'world'
< p > 3) 传递一个函数给JSON

var obj = {
hello: "World",
sayHello: (function() {
console.log("I say Hello!");
}).toString()
};
var myobj = JSON.parse(JSON.stringify(obj));
myobj.sayHello = new Function("return ("+myobj.sayHello+")")();
myobj.sayHello();

我在几行代码中实现了一个相当可靠的解决方案。

有一个像这样的HTML元素,我想传递自定义选项:

<div class="my-element"
data-options="background-color: #dadada; custom-key: custom-value;">
</div>

函数解析自定义选项并返回一个对象以在某处使用:

function readCustomOptions($elem){
var i, len, option, options, optionsObject = {};


options = $elem.data('options');
options = (options || '').replace(/\s/g,'').split(';');
for (i = 0, len = options.length - 1; i < len; i++){
option = options[i].split(':');
optionsObject[option[0]] = option[1];
}
return optionsObject;
}


console.log(readCustomOptions($('.my-element')));
string = "firstName:name1, lastName:last1";

这是可行的:

var fields = string.split(', '),
fieldObject = {};


if( typeof fields === 'object') ){
fields.each(function(field) {
var c = property.split(':');
fieldObject[c[0]] = c[1];
});
}

然而,这并不是有效的。当你有这样的东西时会发生什么:

string = "firstName:name1, lastName:last1, profileUrl:http://localhost/site/profile/1";

split()将拆分'http'。所以我建议您使用一个特殊的分隔符,如pipe

 string = "firstName|name1, lastName|last1";




var fields = string.split(', '),
fieldObject = {};


if( typeof fields === 'object') ){
fields.each(function(field) {
var c = property.split('|');
fieldObject[c[0]] = c[1];
});
}

在你的情况下

var KeyVal = string.split(", ");
var obj = {};
var i;
for (i in KeyVal) {
KeyVal[i] = KeyVal[i].split(":");
obj[eval(KeyVal[i][0])] = eval(KeyVal[i][1]);
}

这是通用代码,不管你的输入有多长,但如果有:分隔符:)

var string = "firstName:name1, lastName:last1";
var pass = string.replace(',',':');
var arr = pass.split(':');
var empty = {};
arr.forEach(function(el,i){
var b = i + 1, c = b/2, e = c.toString();
if(e.indexOf('.') != -1 ) {
empty[el] = arr[i+1];
}
});
console.log(empty)

如果你有一个像foo: 1, bar: 2这样的字符串,你可以用以下方法将它转换为一个有效的obj:

str
.split(',')
.map(x => x.split(':').map(y => y.trim()))
.reduce((a, x) => {
a[x[0]] = x[1];
return a;
}, {});

感谢javascript中的niggler。

更新说明:

const obj = 'foo: 1, bar: 2'
.split(',') // split into ['foo: 1', 'bar: 2']
.map(keyVal => { // go over each keyVal value in that array
return keyVal
.split(':') // split into ['foo', '1'] and on the next loop ['bar', '2']
.map(_ => _.trim()) // loop over each value in each array and make sure it doesn't have trailing whitespace, the _ is irrelavent because i'm too lazy to think of a good var name for this
})
.reduce((accumulator, currentValue) => { // reduce() takes a func and a beginning object, we're making a fresh object
accumulator[currentValue[0]] = currentValue[1]
// accumulator starts at the beginning obj, in our case {}, and "accumulates" values to it
// since reduce() works like map() in the sense it iterates over an array, and it can be chained upon things like map(),
// first time through it would say "okay accumulator, accumulate currentValue[0] (which is 'foo') = currentValue[1] (which is '1')
// so first time reduce runs, it starts with empty object {} and assigns {foo: '1'} to it
// second time through, it "accumulates" {bar: '2'} to it. so now we have {foo: '1', bar: '2'}
return accumulator
}, {}) // when there are no more things in the array to iterate over, it returns the accumulated stuff


console.log(obj)

令人困惑的MDN文档:

演示:http://jsbin.com/hiduhijevu/edit?js,console

功能:

const str2obj = str => {
return str
.split(',')
.map(keyVal => {
return keyVal
.split(':')
.map(_ => _.trim())
})
.reduce((accumulator, currentValue) => {
accumulator[currentValue[0]] = currentValue[1]
return accumulator
}, {})
}


console.log(str2obj('foo: 1, bar: 2')) // see? works!
var stringExample = "firstName:name1, lastName:last1 | firstName:name2, lastName:last2";


var initial_arr_objects = stringExample.split("|");
var objects =[];
initial_arr_objects.map((e) => {
var string = e;
var fields = string.split(','),fieldObject = {};
if( typeof fields === 'object') {
fields.forEach(function(field) {
var c = field.split(':');
fieldObject[c[0]] = c[1]; //use parseInt if integer wanted
});
}
console.log(fieldObject)
objects.push(fieldObject);
});

"objects"数组将包含所有对象

你需要使用JSON.parse()将String转换为Object:

var obj = JSON.parse('{ "firstName":"name1", "lastName": "last1" }');

由于JSON.parse()方法需要将对象键括在引号中才能正确工作,因此在调用JSON.parse()方法之前,我们首先必须将字符串转换为JSON格式的字符串。

var obj = '{ firstName:"John", lastName:"Doe" }';


var jsonStr = obj.replace(/(\w+:)|(\w+ :)/g, function(matchedStr) {
return '"' + matchedStr.substring(0, matchedStr.length - 1) + '":';
});


obj = JSON.parse(jsonStr); //converts to a regular object


console.log(obj.firstName); // expected output: John
console.log(obj.lastName); // expected output: Doe

即使字符串有一个复杂的对象(如下所示),这也可以工作,并且仍然可以正确地转换。只要确保字符串本身是用单引号括起来的。

var strObj = '{ name:"John Doe", age:33, favorites:{ sports:["hoops", "baseball"], movies:["star wars", "taxi driver"]  }}';


var jsonStr = strObj.replace(/(\w+:)|(\w+ :)/g, function(s) {
return '"' + s.substring(0, s.length-1) + '":';
});


var obj = JSON.parse(jsonStr);
console.log(obj.favorites.movies[0]); // expected output: star wars

我正在使用JSON5,它的工作相当好。

好的部分是它包含没有 eval没有 new Function,使用非常安全。

我知道这是一个老帖子,但没有看到这个问题的正确答案。

var jsonStrig = '{';
var items = string.split(',');
for (var i = 0; i < items.length; i++) {
var current = items[i].split(':');
jsonStrig += '"' + current[0] + '":"' + current[1] + '",';
}
jsonStrig = jsonStrig.substr(0, jsonStrig.length - 1);
jsonStrig += '}';
var obj = JSON.parse(jsonStrig);
console.log(obj.firstName, obj.lastName);

现在你可以使用obj.firstNameobj.lastName来获取值,就像你通常对对象所做的那样。

下面是我处理一些边缘情况的方法,比如将空格和其他基本类型作为值

const str = " c:234 , d:sdfg ,e: true, f:null, g: undefined, h:name ";


const strToObj = str
.trim()
.split(",")
.reduce((acc, item) => {
const [key, val = ""] = item.trim().split(":");
let newVal = val.trim();


if (newVal == "null") {
newVal = null;
} else if (newVal == "undefined") {
newVal = void 0;
} else if (!Number.isNaN(Number(newVal))) {
newVal = Number(newVal);
}else if (newVal == "true" || newVal == "false") {
newVal = Boolean(newVal);
}
return { ...acc, [key.trim()]: newVal };
}, {});

在你的情况下,简短而漂亮的代码

Object.fromEntries(str.split(',').map(i => i.split(':')));
const text = '{"name":"John", "age":30, "city":"New York"}';
const myArr = JSON.parse(text);
document.getElementById("demo").innerHTML = myArr.name;