Convert array to JSON

后端 未结 9 1521
南笙
南笙 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:38

    Script for backward-compatibility: https://github.com/douglascrockford/JSON-js/blob/master/json2.js

    And call:

    var myJsonString = JSON.stringify(yourArray);
    

    Note: The JSON object is now part of most modern web browsers (IE 8 & above). See caniuse for full listing. Credit goes to: @Spudley for his comment below

    0 讨论(0)
  • 2020-11-22 04:38

    I decided to use the json2 library and I got an error about “cyclic data structures”.

    I got it solved by telling json2 how to convert my complex object. Not only it works now but also I have included only the fields I need. Here is how I did it:

    OBJ.prototype.toJSON = function (key) {
           var returnObj = new Object();
           returnObj.devid = this.devid;
           returnObj.name = this.name;
           returnObj.speed = this.speed;
           returnObj.status = this.status;
           return returnObj;
       }
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 04:47

    I made it that way:

    if I have:

    var jsonArg1 = new Object();
        jsonArg1.name = 'calc this';
        jsonArg1.value = 3.1415;
    var jsonArg2 = new Object();
        jsonArg2.name = 'calc this again';
        jsonArg2.value = 2.73;
    
    var pluginArrayArg = new Array();
        pluginArrayArg.push(jsonArg1);
        pluginArrayArg.push(jsonArg2);
    

    to convert pluginArrayArg (which is pure javascript array) into JSON array:

    var jsonArray = JSON.parse(JSON.stringify(pluginArrayArg))
    
    0 讨论(0)
  • 2020-11-22 04:48

    Wow, seems it got a lot easier nowadays... 3 ways you can do it:

    json = { ...array };
    
    json = Object.assign({}, array);
    
    json = array.reduce((json, value, key) => { json[key] = value; return json; }, {});
    
    0 讨论(0)
  • 2020-11-22 04:50

    Or try defining the array as an object. (var cars = {};) Then there is no need to convert to json. This might not be practical in your example but worked well for me.

    0 讨论(0)
提交回复
热议问题