key:[id,name,address]
value:[7,John,NewYork]
I wish to create a json data like{"id": 7, "name": "John", "address": "NewYork"}
using for(...){...},
and then return it to ajax
$.ajax({
//what kind of format should json data be here?
data:??json data??,
dataType: 'json',
});
Please help me
The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array.
According to the AJAX model, web applications can send and retrieve data from a server asynchronously without interfering with the display and the behavior of the existing page. Many developers use JSON to pass AJAX updates between the client and the server.
Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type string, number, object, array, boolean or null.
The file is invalid if it contains more than one JSON object. When you try to load and parse a JSON file with multiple JSON objects, each line contains valid JSON, but as a whole, it is not a valid JSON as there is no top-level list or object definition.
To the first part of your question:
You could use Array#forEach()
and assign all properties with the correspondet value.
var key = ['id', 'name', 'address'],
value = [7, 'John', 'New York'],
object = {};
key.forEach(function (k, i) {
object[k] = value[i];
})
document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With