Convert array to JSON

后端 未结 9 1705
南笙
南笙 2020-11-22 04:28

I have an Array var cars = [2,3,..] which holds a few integers. I\'ve added a few values to the array, but I now need to send this array to a page via jQuery\'s

9条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 04:40

    The shortest way I know to generate valid json from array of integers is

    let json = `[${cars}]`
    

    for more general object/array use JSON.stringify(cars) (for object with circular references use this)

    let cars = [1,2,3]; cars.push(4,5,6);
    
    let json = `[${cars}]`;
    
    console.log(json);
    console.log(JSON.parse(json)); // json validation

提交回复
热议问题