1

I have a string in this format:

var x = "a=1; b=2; c=3; d=4"

and I would like to convert it to an object like this:

var y = {
    a: "1",
    b: "2",
    c: "3",
    d: "4"
    }

Any ideas how to achieve that?

6
  • So show us what you have tried so far Commented Sep 10, 2015 at 16:11
  • 2
    i tried x.split(";") wich give me ["a=1", "b=2", "c=3", "d=4"]. and i'm thinking to do another split by "=" for each item in the table... ? Commented Sep 10, 2015 at 16:17
  • 2
    And what's wrong with the solution you're talking about? Commented Sep 10, 2015 at 16:17
  • 1
    benalman.com/news/2010/03/theres-no-such-thing-as-a-json. You want to create a JavaScript object, not JSON. Either way, simply split the string (multiple times) and create a new object from the parts. What exactly are you having problems with? Commented Sep 10, 2015 at 16:21
  • actually, what i'm trying to do is to parse a mail header. here is the function: mailListener.on("mail", function(mail, seqno, attributes){ var dkim = mail.headers["dkim-signature"].split(";") // ..... } since i'm running that in nodejs(asynchronously), it gets messed up as i try to boocle over the table... Commented Sep 10, 2015 at 16:29

3 Answers 3

5

This works in iE9+

var x = "a=1; b=2; c=3; d=4",
    y = {};

x.split(';').map(function (i) {
  return i.split('=')
}).forEach(function (j) {
  y[j[0].trim()] = j[1]
});

If you are using Node.js v4+

let x = "a=1; b=2; c=3; d=4",
    y = {}

x.split(';').map(i => i.split('=')).forEach(j => y[j[0].trim()] = j[1])
Sign up to request clarification or add additional context in comments.

Comments

0

You could try this (not bullet proof, refer to comments):

var json, str;
str = 'a=1; b=2; c=3; d=4';
str = str.replace(/\s*;\s*/g, ',');
str = str.replace(/([^,]+)=([^,]+)/g, '"$1":"$2"');
str = '{' + str + '}';
json = JSON.parse(str);

document.write(
  '<pre>' + JSON.stringify(json) + '</pre>'
);

3 Comments

i get this error {"v":"1," "a":"rsa-sha256," "c":"simple/simple," "d":"X.XXXXX.XXX ^ SyntaxError: Unexpected string
@SoufianeMghanen The input seems to be more complicated than you said x-) Can you post the actual string please?
You would have to escape any " that occurs in the value. You also have to make sure to escape any escape sequences that have a special meaning in JSON and any occurrence of \ otherwise. Also this approach will fail if any of the values itself contains a ,.
-1

here is what i did and it seems to work fine:

var y = x.split(";");
var obj = {};
for(var i = 0; i < y.length ; i++){
    var k = y[i].split("=");
    var r = k[0].replace(" ", "");
    obj[r] = k[1];
}
console.log(obj);

Comments

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.