How to create a JSON object using jQuery

I have a JSON object in the bottom format:

temp:[ { test:'test 1', testData: [ {testName: 'do',testId:''} ], testRcd:'value' }, { test:'test 2', testData: [ {testName: 'do1',testId:''} ], testRcd:'value' } ], 

How to create a JSON object in jquery for the format above. I want to create a dynamic JSON object.

+67
json arrays
Jun 18 '12 at 7:11
source share
5 answers

Just put your data in an object like this:

 var myObject = new Object(); myObject.name = "John"; myObject.age = 12; myObject.pets = ["cat", "dog"]; 

Then tweak it with:

 var myString = JSON.stringify(myObject); 

You do not need jQuery for this. This is pure JS.

+175
Jun 18 '12 at 7:15
source share

A "JSON object" does not make sense: JSON is an exchange format based on the structure of a Javascript object declaration.

If you want to convert your javascript object to a json string, use JSON.stringify(yourObject) ;

If you want to create a javascript object, simply execute it as follows:

 var yourObject = { test:'test 1', testData: [ {testName: 'do',testId:''} ], testRcd:'value' }; 
+25
Jun 18 '12 at 7:15
source share

I believe that he asks to write a new json to the directory. You will need some Javascript and PHP. So, to answer the other answers:

script.js

 var yourObject = { test:'test 1', testData: [ {testName: 'do',testId:''} ], testRcd:'value' }; var myString = 'newData='+JSON.stringify(yourObject); //converts json to string and prepends the POST variable name $.ajax({ type: "POST", url: "buildJson.php", //the name and location of your php file data: myString, //add the converted json string to a document. success: function() {alert('sucess');} //just to make sure it got to this point. }); return false; //prevents the page from reloading. this helps if you want to bind this whole process to a click event. 

buildJson.php

 <?php $file = "data.json"; //name and location of json file. if the file doesn't exist, it will be created with this name $fh = fopen($file, 'a'); //'a' will append the data to the end of the file. there are other arguemnts for fopen that might help you a little more. google 'fopen php'. $new_data = $_POST["newData"]; //put POST data from ajax request in a variable fwrite($fh, $new_data); //write the data with fwrite fclose($fh); //close the dile ?> 
+4
Feb 12 '13 at 21:37
source share

Nested JSON Object

 var data = { view:{ type: 'success', note:'Updated successfully', }, }; 

You can analyze this data.view.type and data.view.note

JSON Object and Internal Array

 var data = { view: [ {type: 'success', note:'updated successfully'} ], }; 

You can analyze this data.view[0].type data.view[0].note and data.view[0].note

0
Mar 07 '17 at 6:33
source share
 var model = {"Id": "xx", "Name":"Ravi"}; $.ajax({ url: 'test/set', type: "POST", data: model, success: function (res) { if (res != null) { alert("done."); } }, error: function (res) { } }); 
-one
Dec 24 '15 at 15:01
source share



All Articles