Hillel Garcia
Hillel Garcia

Reputation: 109

From string to an Object with Javascript

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

Upvotes: 0

Views: 67

Answers (3)

Gilles Quénot
Gilles Quénot

Reputation: 185560

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);
};

Upvotes: 1

user663031
user663031

Reputation:

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

Upvotes: 1

O_Z
O_Z

Reputation: 1563

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 !

Upvotes: -1

Related Questions