1

I have a JSON string as follows:

[
    {"TypeName":"Double","TypeID":14},
    {"TypeName":"Single","TypeID":43},
    {"TypeName":"Family","TypeID":7}
]

It is generated after calling this function in KnockOut:

self.save = function() {
    var dataToSave = $.map(self.lines(), function(line) {
        return line.product() ? {
            TypeName: line.category().TypeName,
            TypeID: line.category().TypeID
            : undefined
});

alert(JSON.stringify(dataToSave));

However, I want to add 3 more pieces of information to the model, before posting it back to my server - to also send Name, Email and Tel:

{
    "Name":"Mark",
    "Email":"[email protected]",
    "Tel":"0123456789",
    "Rooms":
        [
            {"TypeName":"Double","TypeID":14},
            {"TypeName":"Single","TypeID":43},
            {"TypeName":"Family","TypeID":7}
        ]
}

Is there a proper way of adding this information to the JSON, or is it just as simple as:

var toSend = "{\"Name\":\"Mark\":\"Email\":\"[email protected]\", \"Tel\":\"0123456789\",\"Rooms\":"
+ JSON.stringify(dataToSave) + "}"; 

Thank you,

Mark

1
  • I would parse and stringify. Perhaps leave out parsing if possible altogether. Your code seems it should work - learn to love the single quotes though, so that you don't have to escape as much. Commented Mar 22, 2013 at 15:59

2 Answers 2

5

Parse your JSON string using JSON.parse into a valid JS object, add the data to the object as needed, then JSON.stringify it back. A JSON string is just a representation of your data, so you shouldn't rely on modifying it directly.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 - This is the only way to guarantee the JSON stays valid.
This is good advice if you don't have control over the data until after it has been encoded, but that's not the case here. He can simply pass a different structure to the JSON encoder.
3

Why encode to JSON and then modify the resulting string when you can pass the structure you actually want to the JSON encdoder?

var toSend = JSON.stringify({
    Name: "Mark",
    Email: "[email protected]",
    Tel: "0123456789",
    Rooms: dataToSave
});

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.