String to object in JS

590,849

Solution 1

Actually, the best solution is using JSON:

Documentation

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

Share:
590,849

Related videos on Youtube

rahul
Author by

rahul

Updated on March 19, 2022

Comments

  • rahul
    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
      cdleary almost 15 years
      Are name1 and last1 string values or identifiers that have been defined elsewhere?
    • Brad
      Brad almost 7 years
      More data needed... what are you doing to do if the key or the value contain a comma or a colon?
    • bytefish
      bytefish over 5 years
      If your string is not format as JSON, you may have to use RegEp to handler.
  • cdleary
    cdleary almost 15 years
    JSON requires quotations around key values, doesn't it?
  • Breton
    Breton almost 15 years
    this is a potential security hole. I wouldn't reccomend this method at all.
  • Nyambaa
    Nyambaa almost 13 years
    That's not working. It gives you error 'SyntaxError: Unexpected token :'. I've checked it in the Chrome.
  • Jason
    Jason about 12 years
    Hey 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
    Michel over 11 years
    Prefect post. This answer uses the basics of JavaScript very clear and should thereby works in every browser
  • Cody
    Cody about 11 years
    Upvote 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
    SomeShinyObject almost 11 years
    jQuery uses eval. globalEval: /** code **/ window[ "eval" ].call( window, data ); /** more code **/
  • Christian
    Christian almost 11 years
    The solution needs parentheses around it: obj = eval('({' + str + '})');
  • Muhammad Umer
    Muhammad Umer almost 11 years
    need to use regex man to conver it into json then parse it into object.
  • Matej
    Matej over 10 years
    Why 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
    Philippe Leybaert over 10 years
    eval() is built-in. JSON.parse() is not.
  • Admin
    Admin over 10 years
    Everyone 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
    Philippe Leybaert over 10 years
    prc322: 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
    xecute over 10 years
    The string, provided by question owner is not a valid JSON string. So, this code is useless...
  • K2xL
    K2xL over 10 years
    won't allow functions to be passed in though
  • Matej
    Matej over 10 years
    That 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
    Dean Meehan about 10 years
    Can 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
    Noel Abrahams over 9 years
    Doesn'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
    Matej over 9 years
    @NoelAbrahams good observation! Just noticed that, I assumed the string is in JSON format..
  • user2864740
    user2864740 over 9 years
    I 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
    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 on eval 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
    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
    Patrick Graham almost 9 years
    I 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
    Aaron Greenwald almost 9 years
    This 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
    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
    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
    Matej almost 9 years
    Understood @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
    Aaron Greenwald almost 9 years
    var a = "firstName:name1, lastName:last1"; JSON.parse('{' + a + '}') throws an error.
  • Louis
    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
    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
    Ondrej Vencovsky over 8 years
    Just 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
    Admin over 8 years
    In 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
    Derek Henderson almost 8 years
    Everyone 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
    mzalazar over 7 years
    yes, 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
    T.J. Crowder over 7 years
    The OP's string does NOT look like "a JSON string without the curly braces."*. Moreover, eval'ing it will throw a ReferenceError unless name1 and last1 are defined in-scope identifiers.
  • Suncat2000
    Suncat2000 over 7 years
    The 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
    bb216b3acfd8f72cbc8f899d4d6963 over 7 years
    @ChristianKernstock Do you know how many downvotes that would take?
  • Andrew
    Andrew about 7 years
    best answer that actually answers the broader question and not the specific case that your string happens to be formatted as JSON...
  • Alex
    Alex about 7 years
    eval should be avoided at all costs.
  • Brad
    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
    not2qubit over 6 years
    This 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
    corysimmons over 6 years
    Fair 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
    John over 5 years
    +1 for using the data- attribute instead of creating pseudo-custom attributes like some frameworks/libraries.
  • Papi
    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 be security 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
    Cathy Ha over 4 years
    This 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
    Yuki Tanaka almost 4 years
    This 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
    Yazan Najjar almost 4 years
    be careful when using eval it has a lot of issues in javascript
  • Hosana Gomes
    Hosana Gomes about 3 years
    This was the only solution that could directly solve the question, although using eval is dangerous.
  • Pivoman
    Pivoman almost 3 years
    This 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
    Eduardo Lucio almost 3 years
    Currently, 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
    Eonasdan over 2 years
    This would work for a flat object but does not work for more complex cases with sub objects.
  • Ruslan Gorbunov
    Ruslan Gorbunov about 2 years
    point 2 does not work (pasted into the console of the chrome browser and pressed enter)
  • Heri Hehe Setiawan
    Heri Hehe Setiawan about 2 years
    This will only work for simple object values. If we enter things like "google.com" it will break.
  • Mareș Ștefan
    Mareș Ștefan about 2 years
    Does not work for nested objects. Try this: str2obj( 'x:10, y: {z: 10}' )