String to object in JS
Solution 1
Actually, the best solution is using JSON:
JSON.parse(text[, reviver]);
Examples:
1)
var myobj = JSON.parse('{ "hello":"world" }');
alert(myobj.hello); // 'world'
2)
var myobj = JSON.parse(JSON.stringify({
hello: "world"
});
alert(myobj.hello); // 'world'
3) Passing a function to 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();
Solution 2
Your string looks like a JSON string without the curly braces.
This should work then:
obj = eval('({' + str + '})');
Solution 3
If I'm understanding correctly:
var properties = string.split(', ');
var obj = {};
properties.forEach(function(property) {
var tup = property.split(':');
obj[tup[0]] = tup[1];
});
I'm assuming that the property name is to the left of the colon and the string value that it takes on is to the right.
Note that Array.forEach
is JavaScript 1.6 -- you may want to use a toolkit for maximum compatibility.
Solution 4
This simple way...
var string = "{firstName:'name1', lastName:'last1'}";
eval('var obj='+string);
alert(obj.firstName);
output
name1
Solution 5
Since JSON.parse() method requires the Object keys to be enclosed within quotes for it to work correctly, we would first have to convert the string into a JSON formatted string before calling JSON.parse() method.
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
This would work even if the string has a complex object (like the following) and it would still convert correctly. Just make sure that the string itself is enclosed within single quotes.
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
Related videos on Youtube
rahul
Updated on March 19, 2022Comments
-
rahul about 2 years
I have a string as
string = "firstName:name1, lastName:last1";
now I need one object obj such that
obj = {firstName:name1, lastName:last1}
How can I do this in JS?
-
cdleary almost 15 yearsAre name1 and last1 string values or identifiers that have been defined elsewhere?
-
Brad almost 7 yearsMore data needed... what are you doing to do if the key or the value contain a comma or a colon?
-
bytefish over 5 yearsIf your string is not format as JSON, you may have to use RegEp to handler.
-
-
cdleary almost 15 yearsJSON requires quotations around key values, doesn't it?
-
Breton almost 15 yearsthis is a potential security hole. I wouldn't reccomend this method at all.
-
Nyambaa almost 13 yearsThat's not working. It gives you error 'SyntaxError: Unexpected token :'. I've checked it in the Chrome.
-
Jason about 12 yearsHey Cdleary... i wonder if you can help me: stackoverflow.com/questions/9357320/… Sorry couldnt find another way to contact you except thru comments on ur answers
-
Michel over 11 yearsPrefect post. This answer uses the basics of JavaScript very clear and should thereby works in every browser
-
Cody about 11 yearsUpvote for this, ALTHOUGH: var string = "{firstName:'name1', lastName:'last1', f: function(){alert('u got hacked...')}()}"; eval('var obj'+string) This could get you hacked... but I think its worth while because its the only thing that works in some cases.
-
SomeShinyObject almost 11 yearsjQuery uses
eval
.globalEval: /** code **/ window[ "eval" ].call( window, data ); /** more code **/
-
Christian almost 11 yearsThe solution needs parentheses around it:
obj = eval('({' + str + '})');
-
Muhammad Umer almost 11 yearsneed to use regex man to conver it into json then parse it into object.
-
Matej over 10 yearsWhy on earth would you use eval for this? Its 1: inefficient 2: insecure 3: unreadable. See my answer @ stackoverflow.com/a/17597365/666835
-
Philippe Leybaert over 10 yearseval() is built-in. JSON.parse() is not.
-
Admin over 10 yearsEveryone who defends this answer should get minus 10k reputation. Eval is a bad function one should NEVER use. I'm not even talking about the security issues here. One error in the code you try to eval and you will have one hell of debugging. window.JSON is widely support since quite some time: caniuse.com/json Most JS frameworks also support JSON parsing.
-
Philippe Leybaert over 10 yearsprc322: Everyone knows that eval() is not very secure (and that's an understatement), but using eval() is the only correct answer to the question above because the input string is not a valid JSON string AND the input string references other variables by name.
-
xecute over 10 yearsThe string, provided by question owner is not a valid JSON string. So, this code is useless...
-
K2xL over 10 yearswon't allow functions to be passed in though
-
Matej over 10 yearsThat is true, however strictly speaking functions should not be in any JSON objects.. For that you have RPC etc, or if you want, you can pass the prototype of a function to the json, and do
eval
later. -
Dean Meehan about 10 yearsCan anyone explain why eval is a security hole in JS when using console (Chrome) the user could potentially run code whenever they wanted on the browser.. unless of course its used in Node.JS etc.
-
Noel Abrahams over 9 yearsDoesn't answer the question at all I'm afraid. It would be wonderful if everyone changed the question to suit the answer. How do you parse "firstName:name1, lastName:last1"? not '{ "hello":"world" }'.
-
Matej over 9 years@NoelAbrahams good observation! Just noticed that, I assumed the string is in JSON format..
-
user2864740 over 9 yearsI finally down-voted in 2014. This is due to increased restrictions on eval in various environments and tooling; not just a general dislike (which I do have) for eval for this purpose. Also, answers should guard themselves and point out limitations or issues.
-
user2864740 over 9 years@DeanMeehan
eval
allows for the potential abuse of XSS, depending where the string is sourced; even assuming that the local system is itself secure. There is a difference between the user running JS on their own behalf and code being injected into a different context. Putting a general "don't use" restriction oneval
removes a source for another potential exploitation vector. (Granted that many sites still don't safely even generate HTML or JS-in-HTML, YMMV.) -
Alerty about 9 years-1:
eval
prevents the JavaScript compiler from doing optimizations. The engine can only know at runtime since it cheats the lexical scope. -
Patrick Graham almost 9 yearsI found this approach was a good start, so the answer was useful. However, xecute has a valid point that it doesn't accommodate strings that may have commas. You could go down the path of matching quotes if your code needs to handle strings with commas, but you still wont catch cases where the quotes are escaped. Just implement what you need, then stop.
-
Aaron Greenwald almost 9 yearsThis doesn't answer the question, I don't know why it has so many upvotes. The questioner (and myself, I googled and ended up here) have data that doesn't conform to JSON standard so can't be parsed.
-
Matej almost 9 years@aarong yes it doesn't answer the question as i said in the comment above yours. I don't see why you're complaining, it has upvotes because it helped someone solve their problem.
-
Aaron Greenwald almost 9 years@matejkramny Fair point, in my haste I didn't see your comment. Apologies. It may help many who have similar questions, and that's represented in the upvotes you have. I stand by my downvote, though, because the question specifies the string format and for those of us that have the same question as the OP this doesn't answer the question.
-
Matej almost 9 yearsUnderstood @aarong. Not sure what the best step would be to correcting the issue (in the best interest of the community and knowledge base). See the meta question: meta.stackoverflow.com/questions/294414
-
Aaron Greenwald almost 9 yearsvar a = "firstName:name1, lastName:last1"; JSON.parse('{' + a + '}') throws an error.
-
Louis almost 9 years@TravisJ Your comment is just as wrong as this answer. For
JSON.parse
to work, you'd need to be parsing the input'{"firstName":"name1", "lastName":"last1"}'
. Note all the additional quotes. -
Travis J almost 9 years@Louis - Yes, each piece would need to be quoted for it to comply to JSON. If doing that is non trivial then it would be just as hard to wrap the values in quotes as it would to parse the properties manually. I removed my prior comment.
-
Ondrej Vencovsky over 8 yearsJust an idea - instead of second split(':') you could split the string "manually" by FIRST colon using indexOf(":") and consider the part of the string until this colon as key and the rest after the colon as the value.
-
Admin over 8 yearsIn a question of parsing text presented by the asker, questions of "what if" are useless. We can accept the given example as representative of the data or we can simply not answer since there could always be a "what if" that will break the parsing.
-
Derek Henderson almost 8 yearsEveryone knows how to convert stringified JSON to JSON. This question answers an entirely different question. The question is how to convert a string that doesn't represent valid JSON into an object.
-
mzalazar over 7 yearsyes, eval is not evil if you use it on a "controlled" environment (anything but external data like files, network or user input, in that cases it could be dangerous if not "filtered/validated").
-
T.J. Crowder over 7 yearsThe OP's string does NOT look like "a JSON string without the curly braces."*. Moreover,
eval
'ing it will throw aReferenceError
unlessname1
andlast1
are defined in-scope identifiers. -
Suncat2000 over 7 yearsThe poster asked about how to parse an unusual structure that was not valid JSON. @cdleary answered the question very well under the circumstances. xecute: handling a comma in a string would require a quoting or escaping mechanism, beyond the scope of this discussion.
-
bb216b3acfd8f72cbc8f899d4d6963 over 7 years@ChristianKernstock Do you know how many downvotes that would take?
-
Andrew about 7 yearsbest answer that actually answers the broader question and not the specific case that your string happens to be formatted as JSON...
-
Alex about 7 yearseval should be avoided at all costs.
-
Brad almost 7 years
eval()
is not a solution. What's going to happen when the input collides with JS functionality? This isn't just about security, it's about properly working software. It's about separating data from the command. Without that separation, you're basically asking for broken software. -
not2qubit over 6 yearsThis is a totally incomprehensible answer for the average reader. Can you explain what each lines does? And what is the resulting output, given OP's input?
-
corysimmons over 6 yearsFair enough. Typically I don't have time to detail stuff and I'm just dropping helpful bits (specifically in case I run into the same exact SO question down the road), but I gotchu.
-
John over 5 years+1 for using the
data-
attribute instead of creating pseudo-custom attributes like some frameworks/libraries. -
Papi over 5 years
eval()
is the ONLY correct solution provided here. That is going to work without any interaction with the input string.JSON.parse
won't work because there is no quotes around properties. Any splitting by,
or:
won't work because what if it's included in some property or value? Sorry guys :) @PhilippeLeybaert is right here. What might work and won't besecurity hole
could be a custom parser that will watch for all closing/open/nested quotes/brackets and so on. Possible to do. Worth it? Depends. -
Cathy Ha over 4 yearsThis is definitely the most elegant solution and actually answers the question unlike a lot of the other answers. And thank you for the explanation!
-
Yuki Tanaka almost 4 yearsThis works fine for me though I'm still not sure why string text is recognised as object when parsing and need to stringify first...
-
Yazan Najjar almost 4 yearsbe careful when using eval it has a lot of issues in javascript
-
Hosana Gomes about 3 yearsThis was the only solution that could directly solve the question, although using eval is dangerous.
-
Pivoman almost 3 yearsThis is the closest solution without using eval() and almost works with all JS Objects in String. But beware, that this solution is not working with timestamps as values! i.e. {from:"2021-05-09T22:00:00.000Z"} is probably converted as {"from":"2021-05-09T"22":"00":00.000Z"}
-
Eduardo Lucio almost 3 yearsCurrently, any JS code executed in the browser is dangerous. Let's be frank... This answer is the only solution that could effectively solve the question "string to object in JS".
JSON.parse()
is limited to the scope of JSON. Remembering that a JSON is not a JS Object. Thanks! =D -
Eonasdan over 2 yearsThis would work for a flat object but does not work for more complex cases with sub objects.
-
Ruslan Gorbunov about 2 yearspoint 2 does not work (pasted into the console of the chrome browser and pressed enter)
-
Heri Hehe Setiawan about 2 yearsThis will only work for simple object values. If we enter things like "google.com" it will break.
-
Mareș Ștefan about 2 yearsDoes not work for nested objects. Try this: str2obj( 'x:10, y: {z: 10}' )