Как создать объект JSON с помощью jQuery
У меня есть объект JSON в нижнем формате:
temp:[
{
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
},
{
test:'test 2',
testData: [
{testName: 'do1',testId:''}
],
testRcd:'value'
}
],
Как создать объект JSON в jquery для формата выше. Я хочу создать динамический объект JSON.
Ответы
Ответ 1
Просто поместите свои данные в объект следующим образом:
var myObject = new Object();
myObject.name = "John";
myObject.age = 12;
myObject.pets = ["cat", "dog"];
Затем подстройте его с помощью:
var myString = JSON.stringify(myObject);
Для этого вам не нужен jQuery. Это чистый JS.
Ответ 2
"Объект JSON" не имеет смысла: JSON - это формат обмена, основанный на структуре объявления объекта Javascript.
Если вы хотите преобразовать свой javascript-объект в строку json, используйте JSON.stringify(yourObject)
;
Если вы хотите создать объект javascript, просто выполните его следующим образом:
var yourObject = {
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
};
Ответ 3
Я считаю, что он просит написать новый 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
?>
Ответ 4
Вложенный 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
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) {
}
});