0

I'm struggling to correctly format some dynamic data from js (I will send it to php later on).

I need it with the following format:

{ "r" : "pax" , "c" : 1 , "w" : [ "kiwi" , "melon"] , "g" : [ "cat" , "dog"]}

And currently am using:

var send = [];
send.push ('r:pax');
send.push ('c:1');


var w = ["kiwi", "melon"];
send.push('"w":'+w);

var g = ["cat", "dog"];
send.push('"g":'+g);

s=JSON.stringify(send);

document.getElementById("demo").innerHTML = s;

Which returns:

["r:pax","c:1","\"w\":kiwi,melon","\"g\":cat,dog"]

I've seen that stringify is the solution, however I can't get to correctly pass keypairs correctly.

how can I do this?

Regards.

1
  • Use an object instead of an array: var send = {}; send.r = 'pax'; send.g = ['cat', 'dog']; etc. Commented Nov 10, 2014 at 20:19

3 Answers 3

2

mmm why are you starting with an array anyway? ... if I understood well this can be easily solved using:

var s = JSON.stringify({
    r: "pax", 
    c: 1,
    w: ["kiwi", "melon"],
    g: ["cat", "dog"]
});
Sign up to request clarification or add additional context in comments.

1 Comment

Hello, the reason I needed to add as array is because data is dynamic, it might just be 2 elements as well as 100. Regards
0

Send shouldn't be an array, according to the format that you want your final output to be, but an object. Something like the following:

var send = {
    r: "pax",
    c: 1,
    w: ["kiwi", "melon"],
    g: ["cat", "dog"]
};

var s = JSON.stringify(send);

Comments

0

You're building the JSON incorrect, by doing it small parts. Just build a NORMAL Javascript array/object pair, then encode the ENTIRE thing to json afterwards.

Because you're passing in key:value strings, json's stringify doesn't know/care that it already is json. It just sees a string and applies string encoding rules to it. Hence all the extra escapes you're seeing.

Try

send = [];
send.push({w:['kiwi', 'melon']})
send.push({g:['cat','dog']});
s = JSON.stringify(send);

instead.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.