0

How can I convert this string: "{one=1,two=2}" into an object with JavaScript? So I can access the values.

I tried replacing the "=" for ":", but then while accessing the object I receive an "undefined". Here is my code:

var numbers = "{one=1,two=2}"; //This is how I receive the string

numbers = numbers.replace(/=/g, ':'); //I use the '/g' to replace all the ocurrencies

document.write(numbers.one); //prints undefined
3
  • JSON field names must have double quotes around them. Commented Sep 25, 2016 at 11:59
  • you are treating string as dictionary/JSON . So numbers.one will be always return undefined. If you want to use in this manner then you should convert string to JSON. Commented Sep 25, 2016 at 12:05
  • Where did this string come from? Commented Sep 25, 2016 at 13:57

3 Answers 3

1

So this is the string

var str = '{one=1,two=2}';

replace = character to : and also make this as a valid JSON object (needs keys with double-quotes around)

var str_for_json = str.replace(/(\w+)=/g, '"$1"=').replace(/=/g, ':');

In , \w means [a-zA-Z0-9_] and the ( ) capture what's inside, usable later like here with $1

Now parse your string to JSON in order to use like that

var str_json = JSON.parse(str_for_json);

Now enjoy. Cheers!!

document.write(str_json.one); 

FINALLY :

var str = '{one=1,two=2}';
var str_for_json = str.replace(/(\w+)=/g, '"$1"=').replace(/=/g, ':');
try {
    var str_json = JSON.parse(str_for_json);   
    document.write(str_json.one);
} catch(e) {
    console.log("Not valid JSON:" + e);
};
Sign up to request clarification or add additional context in comments.

2 Comments

It works thank you. Can you explain this part?: (\w+)
@HillelGarcia : I think you are not fully aware of regex. Have a practice for it. hackerrank.com/domains/regex
1

Instead of trying to use regexp to create JSON, I would simply parse the string directly, as in

const result = {};

numbers.match(/{(.*?)}/)[1]             // get what's between curlies
  .split(',')                           // split apart key/value pairs
  .map(pair => pair.split('='))         // split pairs into key and value
  .forEach(([key, value]) =>            // for each key and value
    result[key] = value);               // set it in the object

1 Comment

The only ES6 feature here is parameter deconstructing (the [key, value] part). If need be, replace that with forEach(pair => result[pair[0]] = pair[1]).
-1

1 - a valide JSON is :var numbers = "{\"one\"=1,\"two\"=2}"; (you need the \")

2- you need to JSON.parse the strign

So this works:

var numbers = "{\"one\"=1,\"two\"=2}"; //This is how I receive the string
numbers = numbers.replace(/=/g, ':'); //I use the '/g' to replace all the ocurrencies
numbers=JSON.parse(numbers);
document.write(numbers.one); //prints undefined 

But, it's bad practice !

2 Comments

So, what is the best practice? I also dont like it, but it works.
But he's not receiving the string with the property names quoted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.