如何使用jQuery创buildJSON对象
我有一个以下格式的JSON对象:
temp:[ { test:'test 1', testData: [ {testName: 'do',testId:''} ], testRcd:'value' }, { test:'test 2', testData: [ {testName: 'do1',testId:''} ], testRcd:'value' } ],
我如何创buildJSON对象在jquery上面的格式。 我想创build一个dynamic的JSON对象。
只要把你的数据放入一个Object就可以了:
var myObject = new Object(); myObject.name = "John"; myObject.age = 12; myObject.pets = ["cat", "dog"];
之后通过以下方式对其进行串化
var myString = JSON.stringify(myObject);
你不需要这个jQuery。 这是纯粹的JS。
“JSON对象”没有任何意义: JSON是基于Javascript对象声明结构的交换格式。
如果你想把你的javascript对象转换成jsonstring,使用JSON.stringify(yourObject)
;
如果你想创build一个javascript对象,只需要这样做:
var yourObject = { test:'test 1', testData: [ {testName: 'do',testId:''} ], testRcd:'value' };
我相信他是要求将新的json写入一个目录。 您将需要一些Javascript 和 PHP。 所以,要捎带回答其他答案:
的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 ?>
嵌套的JSON
对象
var data = { view:{ type: 'success', note:'Updated successfully', }, };
你可以parsing这个data.view.type
和data.view.note
JSON
对象和内部数组
var data = { view: [ {type: 'success', note:'updated successfully'} ], };
你可以parsing这个data.view[0].type
和data.view[0].note
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) { } });