Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
157
rated 0 times [  159] [ 2]  / answers: 1 / hits: 57831  / 12 Years ago, fri, may 11, 2012, 12:00:00

I want to build a JSON string programmatically. The end product should be something like this:


var myParamsJson = {first_name: "Bob", last_name: "Smith" };

However, I would like to do it one parameter at a time. If it were an array, I would do something like this:


var myParamsArray = [];
myParamsArray["first_name"] = "Bob";
myParamsArray["last_name"] = "Smith";

I wouldn't even mind building that array and then converting it to JSON.


More From » json

 Answers
111

You could do a similar thing with objects:



var myObj = {};
myObj[first_name] = Bob;
myObj[last_name] = Smith;


and then you could use the JSON.stringify method to turn that object into a JSON string.



var json = JSON.stringify(myObj);
alert(json);


will show:



{first_name:Bob,last_name:Smith}


This method is natively built into all modern browsers (even IE8 supports it, even if IE8 is very far from being a modern browser). And if you need to support some legacy browsers you could include the json2.js script.


[#85637] Thursday, May 10, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alejandro

Total Points: 231
Total Questions: 102
Total Answers: 107

Location: Jordan
Member since Wed, Jun 17, 2020
4 Years ago
alejandro questions
Mon, Jul 18, 22, 00:00, 2 Years ago
Fri, Sep 18, 20, 00:00, 4 Years ago
Thu, Sep 10, 20, 00:00, 4 Years ago
;