是否可以在 json 中存储 javascript 数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12757482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:02:59  来源:igfitidea点击:

is it possible to store javascript array in json?

javascriptjqueryjsondom

提问by Peter Wateber

Possible Duplicate:
Convert Javascript Array to JSON

可能的重复:
将 Javascript 数组转换为 JSON

I am trying to figure out how to return an array and store it in json variable as string, is that possible? [If not, how can I return all the outputs and store it json?] - If you know what I mean...

我想弄清楚如何返回一个数组并将其作为字符串存储在 json 变量中,这可能吗?[如果没有,我如何返回所有输出并将其存储为 json?] - 如果你知道我的意思......

    //arr = ["a", "b", "c", "d", "ddd"]
    //largest = 3
    var generateEntryCodes = function(arr, largest) {
        var newText = ""
        for(var i=0; i < arr.length; i++) {
            if (arr[i] == null) {
                arr.splice(i, 1);
                i--;
            }
            var counts = arr[i].length != largest ? (parseInt(largest) - parseInt(arr[i].length)) : 0
            for (var z=0; z<counts;z++)
                newText += "0"
            var result = arr[i].splice( 0, 0, newText )
            newText = ""
            result = [{
                "result": result, 
                "total": result.length
            }]
        }
        return result
    }

I am try to output the above code as:

我尝试将上述代码输出为:

00a
00b
00c
00d
ddd

But as I flash the result json. I only get "ddd"... So I tried adding before the result = [{}]jSON code:

但是当我刷新结果json时。我只得到“ddd”...所以我尝试在result = [{}]jSON 代码之前添加:

$("textarea").val( $("textarea").val("") + result + "\n")
//outputs:
   00a
   00b
   00c
   00d
   ddd

How can I get all the outputs from resultvariable and store it in JSONvariable.

如何从结果变量中获取所有输出并将其存储在JSON变量中。

Problem: Code only store into JSON the last array.

问题:代码仅将最后一个数组存储到 JSON 中。

回答by Juri

Generally speaking you can simply construct your JavaScript object and then serialize it to JSON like in the example below:

一般来说,您可以简单地构建 JavaScript 对象,然后将其序列化为 JSON,如下例所示:

var myArray = ['a','b','c'];
var jsonString = JSON.stringify(myArray);

That should work. Note that you might have to include JSON2.jsin case your browser doesn't support it natively.

那应该有效。请注意,您可能必须包含JSON2.js,以防您的浏览器本身不支持它。

//Edit:
That should work: http://jsbin.com/welcome/31083/edit

//编辑:
这应该有效:http: //jsbin.com/welcome/31083/edit

Here's the code:

这是代码:

var generateEntryCodes = function(arr, largest) {
        var newText = "",
            codes = [],
            currentElement,
            result;


        for(var i=0; i < arr.length; i++) {
          currentElement = arr[i];

          var zerosToPrepend = largest - currentElement.length;
          for (var z = 0; z < zerosToPrepend; z++){
                newText += "0"
          }

          currentElement = newText + currentElement;
          codes.push(currentElement);    

          newText = ""
        }

      result = {
        codes: codes,
        total: codes.length
      };

        return result
    }


var result = generateEntryCodes(["a", "b", "c", "d", "ddd"], 3);
console.log(result);

This should return a JavaScript object that looks as follows:

这应该返回一个如下所示的 JavaScript 对象:

{"codes": ["00a", "00b", "00c", "00d", "ddd"], "total": 5}

You can then take that result and use JSON.stringify(...)to convert it into a JSON string.

然后,您可以获取该结果JSON.stringify(...)并将其转换为 JSON 字符串。

回答by StaticVariable

if you have string like aaa bbb cccthan first convert it into array

如果你有字符串aaa bbb ccc比先把它转换成数组

var str="aaa bbb ccc ddd";
var n=str.split(" ");

Now can use JSON.stringify(string)to convert string into json

现在可以JSON.stringify(string)用来将字符串转换为 json

var myjson=JSON.stringify(n);