Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a json data using two arrays and return it to ajax

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

like image 575
peter Avatar asked Apr 30 '16 14:04

peter


People also ask

How JSON fetch data using AJAX?

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.

Can you use JSON with AJAX?

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.

Can JSON have array of arrays?

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.

Can JSON containing multiple objects?

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.


1 Answers

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>');
like image 94
Nina Scholz Avatar answered Sep 24 '22 07:09

Nina Scholz