我有一个以下格式的JSON对象:
temp:[
{
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
},
{
test:'test 2',
testData: [
{testName: 'do1',testId:''}
],
testRcd:'value'
}
],
Run Code Online (Sandbox Code Playgroud)
如何在jquery中为上述格式创建JSON对象.我想创建一个动态JSON对象.
Tim*_*Tim 205
只需将您的数据放入对象中,如下所示:
var myObject = new Object();
myObject.name = "John";
myObject.age = 12;
myObject.pets = ["cat", "dog"];
Run Code Online (Sandbox Code Playgroud)
然后通过以下方式进行字符串化
var myString = JSON.stringify(myObject);
Run Code Online (Sandbox Code Playgroud)
你不需要jQuery.这是纯粹的JS.
Den*_*ret 31
"JSON对象"没有意义:JSON是基于Javascript对象声明结构的交换格式.
如果要将javascript对象转换为json字符串,请使用JSON.stringify(yourObject);
如果你想创建一个javascript对象,只需这样做:
var yourObject = {
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
};
Run Code Online (Sandbox Code Playgroud)
我相信他要求将新的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.
Run Code Online (Sandbox Code Playgroud)
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
?>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
250183 次 |
| 最近记录: |