将键值数组存储到紧凑的JSON字符串中

uml*_*cat 17 json key-value

我想存储一组键值项,常见的方法可能是:

// the JSON data may store several data types, not just key value lists,
// but, must be able to identify some data as a key value list

// --> more "common" way to store a key value array
{
  [
    {"key": "slide0001.html", "value": "Looking Ahead"},
    {"key": "slide0008.html", "value": "Forecast"},
    {"key": "slide0021.html", "value": "Summary"},
    // another THOUSANDS KEY VALUE PAIRS
    // ...
  ],
  "otherdata" : { "one": "1", "two": "2", "three": "3" }
}
Run Code Online (Sandbox Code Playgroud)

但是,当有很多对/项目时,字符串长度变得禁止,我想要一个紧凑的方式,这可能是一个例子:

// --> (1) a "compact" way to store a key value array
{    
  [
      {"slide0001.html", "Looking Ahead"},
      {"slide0008.html", "Forecast"},
      {"slide0021.html", "Summary"},
      // another THOUSANDS KEY VALUE PAIRS
      // ...
  ],
  "otherdata" : { "one": "1", "two": "2", "three": "3" }
}
Run Code Online (Sandbox Code Playgroud)

另外,我想要一种方法将数据标识为keyvalue数组,因为,我可能希望将其他数据存储在同一个JSON文件中.我有这些例子:

// --> (2) a "compact" way to store a key value array    
{
    "keyvaluelist":
    [
      {"slide0001.html", "Looking Ahead"},
      {"slide0008.html", "Forecast"},
      {"slide0021.html", "Summary"},
      // another THOUSANDS KEY VALUE PAIRS
      // ...
    ],
    "otherdata" : { "one": "1", "two": "2", "three": "3" }
}

// --> (3) a "compact" way to store a key value array    
{
    "mylist":
    {
      "type": "keyvaluearray",
  "data":
    [
        {"slide0001.html", "Looking Ahead"},
        {"slide0008.html", "Forecast"},
        {"slide0021.html", "Summary"},
                    // another THOUSANDS KEY VALUE PAIRS
                    // ...
    ]
    },
    "otherdata" : { "one": "1", "two": "2", "three": "3" }
}
Run Code Online (Sandbox Code Playgroud)

你有什么建议,你建议哪一个,你有另一种方式吗?谢谢.

更新1:删除无效代码.Javascript => JSON

更新2:添加非键值数据

更新3:将"["和"]"替换为每个键值对中的"{"和"}"

Cro*_*zin 16

那你为什么不简单地使用键值文字呢?

var params = {
    'slide0001.html': 'Looking Ahead',
    'slide0002.html': 'Forecase',
    ...
};

return params['slide0001.html']; // returns: Looking Ahead
Run Code Online (Sandbox Code Playgroud)


rid*_*rid 13

如果解析它的逻辑知道{"key": "slide0001.html", "value": "Looking Ahead"}是一个键/值对,那么你可以在一个数组中转换它并保存一些常量,指定哪个索引映射到哪个键.

例如:

var data = ["slide0001.html", "Looking Ahead"];

var C_KEY = 0;
var C_VALUE = 1;

var value = data[C_VALUE];
Run Code Online (Sandbox Code Playgroud)

那么,现在,您的数据可以是:

[
    ["slide0001.html", "Looking Ahead"],
    ["slide0008.html", "Forecast"],
    ["slide0021.html", "Summary"]
]
Run Code Online (Sandbox Code Playgroud)

如果您的解析逻辑没有提前知道数据结构,您可以添加一些元数据来描述它.例如:

{ meta: { keys: [ "key", "value" ] },
  data: [
    ["slide0001.html", "Looking Ahead"],
    ["slide0008.html", "Forecast"],
    ["slide0021.html", "Summary"]
  ]
}
Run Code Online (Sandbox Code Playgroud)

...然后由解析器处理.