简体   繁体   English

用Javascript构建复杂的JSON

[英]Building complex JSON in Javascript

Just started using JavaScript and need some guidance on how best to create /build the JSON below on the fly/dynamically. 刚开始使用JavaScript,并需要一些有关如何最佳地动态/动态创建/构建JSON的指导。

Some of the keys will need to be from variables. 一些键将需要来自变量。 For example in the JSON below, keys called 'variable_key_*' will need to be from a variable. 例如,在下面的JSON中,名为“ variable_key_ *”的键将需要来自变量。

{
  "static_key_1": "value",
  "static_key_2": [{
    "static_key_3": {
      "id": "1097274153"
    },
    "static_key_4": "value",
    "static_key_5": {
      "static_key_6": {
        "variable_key_1": "value",
        "variable_key_2": "value",
        "variable_key_3": "value"
      },
      "static_key_7": {
        "static_key_8": [
          "value"
        ]
      }
    }
  }]
}

You can set keys in an object with variables by using bracket notation. 您可以使用方括号表示法在具有变量的对象中设置键。

let theVariable = 'useful_name';
let theValue = 12345;
let myObj = {};

myObj [ theVariable ] = theValue;

Will result in: 将导致:

{ useful_name : 12345 }

And stringify as you'd expect. 并按照您的期望进行分类。

Edit based on request for more info: 根据要求编辑以获取更多信息:

Say you wanted to create a nested object with an array of objects, we'll use the object we already have. 假设您要创建带有对象数组的嵌套对象,我们将使用已有的对象。

myObj [ someOtherVar ] = {};
let myObjSomeOtherVar = myObj [ someOtherVar ];
myObjSomeOtherVar [ someOtherKey ] = [ ].push ( { } );
let theArrayOfObjects = myObjSomeOtherVar [ someOtherKey ];
theArrayOfObjects [ 0 ] [ anotherKeyName ] = 'hello';

This would result in (provided you actually declared all the vars etc) 这将导致(假设您实际上声明了所有var等)

{ useful_name : 12345,
  valOfSomeOtherVar : 
      { valOfSomeOtherKey : 
          [ { valOfAnotherKeyName : 'hello' } ] 
      }
} 

The trick is to just develop your data schema abstractly (so the skeleton you want), then write a routine that builds it. 诀窍是只抽象地开发数据模式(即所需的框架),然后编写一个构建它的例程。 I rarely build an object by hand this way unless it's just a small util obj, I usually feed an empty object into a routine to build it out (using loops, recursion, conditionals, whatever). 除非它只是一个小的util obj,否则我很少以这种方式手动构建对象,我通常将一个空对象馈送到例程中以进行构建(使用循环,递归,条件等)。 And as for practice, it is always a good idea to have a skeleton at least documented for a data structure, which can also be used as reference to write the function that can generate the whole thing just by passing it some variables for keynames and values. 在实践中,最好至少为数据结构记录一个骨架,这也可以用作编写可以通过传递一些键名和值变量来生成整个函数的函数的参考。 。 You would write a test for that function that would give you back the objects you'd predict, etc. 您将为此功能编写一个测试,该测试将返回您所预测的对象,等等。

If you don't need to create it in one statement (and there is few chance you do), you'd do as follow: 如果您不需要在一个语句中创建它(并且几乎没有机会这样做),则可以执行以下操作:

var yourObject = {
  "static_key_1": "value",
  "static_key_2": [{
    "static_key_3": {
        "id": "1097274153"
    },
    "static_key_4": "value",
    "static_key_5": {
        "static_key_6": {},
        "static_key_7": {
            "static_key_8": [
                "value"
            ]
         }
     }
  }]
}

/* Get their value from wherever you want */
var variable_key_1 = 'something';
var variable_key_2 = 'something_else';
var variable_key_3 = 'another_one';

yourObject.static_key_2[0].static_key_5.static_key_6[variable_key_1] = 'value';
yourObject.static_key_2[0].static_key_5.static_key_6[variable_key_2] = 'value';
yourObject.static_key_2[0].static_key_5.static_key_6[variable_key_3] = 'value';

The strategy is to build the objects with properties with variables names after the ones with static names, using the brackets notation. 策略是使用方括号表示法在具有静态名称的对象之后构建具有变量名称的属性的对象。

This will result in: 这将导致:

{
  "static_key_1": "value",
  "static_key_2": [{
    "static_key_3": {
        "id": "1097274153"
    },
    "static_key_4": "value",
    "static_key_5": {
        "static_key_6": {
          "something": "value",
          "something_else": "value",
          "another_one": "value"
        },
        "static_key_7": {
            "static_key_8": [
                "value"
            ]
         }
     }
  }]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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