我有以下格式的JSON对象:
temp:[
{
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
},
{
test:'test 2',
testData: [
{testName: 'do1',testId:''}
],
testRcd:'value'
}
],
如何在jquery中为上述格式创建JSON对象。我想创建一个动态JSON对象。
答案 0 :(得分:198)
只需将您的数据放入这样的对象:
var myObject = new Object();
myObject.name = "John";
myObject.age = 12;
myObject.pets = ["cat", "dog"];
然后通过:
进行字符串化var myString = JSON.stringify(myObject);
你不需要jQuery。这是纯粹的JS。
答案 1 :(得分:30)
“JSON对象”没有意义:JSON是基于Javascript对象声明结构的交换格式。
如果要将javascript对象转换为json字符串,请使用JSON.stringify(yourObject)
;
如果你想创建一个javascript对象,只需这样做:
var yourObject = {
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
};
答案 2 :(得分:5)
我相信他要求将新的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
?>
答案 3 :(得分:1)
如何获取像json这样的追加输入字段值
temp:[
{
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
},
{
test:'test 2',
testData: [
{testName: 'do1',testId:''}
],
testRcd:'value'
}
],
答案 4 :(得分:0)
嵌套JSON
对象
var data = {
view:{
type: 'success', note:'Updated successfully',
},
};
您可以解析此data.view.type
和data.view.note
JSON
对象和内部数组
var data = {
view: [
{type: 'success', note:'updated successfully'}
],
};
您可以解析此data.view[0].type
和data.view[0].note
答案 5 :(得分:-1)
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) {
}
});