As you can read this JSON using jQuery or JavaScript. I never use JSON.
{
"ES": {
"130": {
"code": "A Coruсa",
"name": "A Coruña"
},
"131": {
"code": "Alava",
"name": "Alava"
},
"132": {
"code": "Albacete",
"name": "Albacete"
}
To a select
:
<select id="provincias">
<option value="130">A Coruña</option>
<option value="131">Alava</option>
<option value="132">Albacete</option>
</select>
You do something like this using jQuery.map()
var data = { "ES": { "130": { "code": "A Coruсa", "name": "A Coruña" }, "131": { "code": "Alava", "name": "Alava" }, "132": { "code": "Albacete", "name": "Albacete" } } }; // generate dropddown $('<select/>', { // setting id attribute id: 'provincias', // setting html content, iterating over JSON to add options html: $.map(data.ES,function(v,i) { // creating otions return $('<option/>', { // setting value as index in json value: i, // setting text content text: v.name }) }) //appending the generated dropdown to the body }).appendTo('body');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
You can make use of recursion:
var data = { "ES": { "130": { "code": "A Coruсa", "name": "A Coruña" }, "131": { "code": "Alava", "name": "Alava" }, "132": { "code": "Albacete", "name": "Albacete" } } }; function setOptions(data) { // get data in the args var option = ''; // create a var to hold the options to be created. for (key in data) { // use for in loop to get the key and values if (data[key].constructor === Object) { // check if data is an object option += '<option value="' + key + '">' + data[key].name + '</option>'; // create option setOptions(data[key]); // pass the object again in the same function to get the "name" value. } } document.getElementById('provincias').innerHTML = option; // finally push in the dom. } setOptions(data.ES); // pass the data here, we're targeting ES5
<select id="provincias"> </select>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.