简体   繁体   中英

json obj into javascript array

I have this json file

[
{"name": "name1", "start": "01/03/2017", "end": "01/03/2017"},
{"name": "name2", "start": "01/03/2017", "end": "01/03/2017"},
{"name": "name3", "start": "01/03/2017", "end": "01/03/2017"}
]

and -i need this result in javascript

var cubes = [
    {name: "name1", start: "01/03/2017", end: "01/25/2017"},
    {name: "name2", start: "01/04/2017", end: "01/26/2017"},
    {name: "name1", start: "06/15/2017", end: "06/18/2017"},    
    {name: "name3", start: "01/05/2017", end: "01/27/2017"}
];

I have:

cubes = [];

$.getJSON('urlaub.json', function(data) {

    var obj = data;
    for (elem in obj) {
        console.log(obj[elem]);
       cubes.push(obj[elem]);
    };
});

But Array cubes is ever empty and .json firefox means syntax error in json File Line 1. But Objects were created. Array is ever empty.Tryed so many. What is wrong?

JSON.parse is as @kukkuz said is what you are after

var data = JSON.parse(`[
    {"name": "name1", "start": "01/03/2017", "end": "01/03/2017"},
    {"name": "name2", "start": "01/03/2017", "end": "01/03/2017"},
    {"name": "name3", "start": "01/03/2017", "end": "01/03/2017"}
]`)

console.log(data); //shows an array

For clarity, the backtick ` is there to allow this to be on multiple lines. You could simply reduce this to a single line and add normal single quotes.

To use your example -

var cubes = null;

function getMyData() { 
    return $.getJSON('urlaub.json', function(data) {
       return data;
    }).error(function(err) { alert("error - " + err) });
};

getMyData().then(function(data){
    cubes = JSON.parse(data);
});
cubes = [];
$.getJSON('urlaub.json', function(data) {
    var obj = data;
    for (elem in obj) {
        debugger
       cubes.push(obj[elem]);
        console.log(obj[elem]);
    };
    console.log(cubes);
});

i tried the above code it worked!!

Docs for $.getJSON :

var cubes = null;
$.getJSON('urlaub.json', function(data) {
    cubes = data;
    console.log(cubes);
});

sorry @ll. All your solutions works, my one too. i was programming on an other working station. so i always saved the wrong files o O.

Please, im sorry. but much thanks for your help.

Thank you very much

thanks,

var arr = [];     
var obj = data;     
$.each(obj,function(key,value){      
    arr.push("< LI>" + value + "< /LI>");      
});     
var val=arr.join('');      
console.log(val);

try it.

replace LI with li

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM