JavaScript - 创建一个空的 json 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30031240/
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-08-23 04:32:02  来源:igfitidea点击:

JavaScript- Create an empty json array

javascriptarraysjson

提问by sarit rotshild

I have to create an empty array with the following keys: "id", "action". How do I create it?

我必须使用以下键创建一个空数组:“id”、“action”。我如何创建它?

回答by daxeh

Assuming to be placed in a variable, because you have 'json' tagged. The following is some explanation of each step of a simple example breakdown:

假设被放置在一个变量中,因为你有 'json' 标记。以下是对简单示例细分的每个步骤的一些解释:

// create an empty array
var array = [];

// create an object with properties "id", "action" with mock values
var object = {
  id: "1",
  action: "shout" 
}

// add object to array
array.push(object);

// create encode json string
var myJSONString = JSON.stringify(array);

Hope this helps.

希望这可以帮助。

回答by RafaelKr

Do you mean this?

你是这个意思吗?

JSON.stringify({
    id: null,
    action: null
})

回答by Mladen Or?oli?

Here is pure JSON example with sample data that should give you guidance

这是带有示例数据的纯 JSON 示例,可以为您提供指导

{
  "object": [
    {
      "Id": "1",
      "action": "New"
    },
    {
      "Id": "2",
      "action": "Open"
    },
    {
      "Id": "3",
      "action": "Close"
    }
  ]
}