1

I need a simple code example showing javascript object and converting it to JSON.... I have done conversion based on javascript Array to JSON using $.ParseJSON(array mentioned here)....Now i need reverse of it...In the end I need to send it to the server using post method...Kindly Guide.

This code i got on internet...

var jsonArg1 = new Object();
    jsonArg1.name = 'calc this';
    jsonArg1.value = 3.1415;
var jsonArg2 = new Object();
    jsonArg2.name = 'calc this again';
    jsonArg2.value = 2.73;

var pluginArrayArg = new Array();
    pluginArrayArg.push(jsonArg1);
    pluginArrayArg.push(jsonArg2);

to convert pluginArrayArg (which is pure javascript array) into JSON array:

var jsonArray = JSON.parse(JSON.stringify(pluginArrayArg))

Here is one of the code that I saw on internet...but it seems as if in the start they are declaring JSON and not the assocaite array elements...Kindly guide me the proper way.Thanks

raduns
  • 765
  • 7
  • 18
Shahroon
  • 11
  • 1
  • 2
  • I think you have to first get the terminology straight. [There is no such thing as a "JSON object" or "array"](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/). There are only JavaScript objects/arrays and JSON. You can parse a *string* containing JSON to a JS object/array using `JSON.parse`. You can convert a JS object/array to a string using `JSON.stringify`. What do you want to do? – Felix Kling Aug 01 '13 at 09:11

1 Answers1

1

In the code above, at the start they are not declaring JSONS its called javascript object..Javascript object is different from Json.To find the difference between the both check What's the difference between Javascript Object and JSON object

To convert javscript object or array to json, use JSON.stringify(varname) . Also, to print objects in javascript use console.log(objname). Add this to your code,

var jsonArg1 = new Object();
jsonArg1.name = 'calc this';
jsonArg1.value = 3.1415;
var jsonArg2 = new Object();
jsonArg2.name = 'calc this again';
jsonArg2.value = 2.73;
var pluginArrayArg = new Array();
pluginArrayArg.push(jsonArg1);
pluginArrayArg.push(jsonArg2);
console.log(pluginArrayArg);
var jsonArray = JSON.stringify(pluginArrayArg);
alert(jsonArray);

Also, to convert an associative array in javascript to JSON, try this example..

var asscArr = {};
asscArr["name"] = "Hello World";
console.log("name = " + asscArr["name"]);
var jsonArr = JSON.stringify(asscArr);
alert(jsonArr);
Community
  • 1
  • 1
raduns
  • 765
  • 7
  • 18