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

标签 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" }
}


但是,如果有很多对/项目,则字符串长度会被禁止,
我想要一个紧凑的方法,这可能是一个示例:

// --> (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" }
}


另外,我想要一种将数据标识为键值数组的方法,
因为,我可能想将其他数据存储在同一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" }
}


您有什么建议,您建议哪个,还有其他方法吗?
谢谢。

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

更新2:添加非键值数据

更新3:在每个键值对中将“ [”和“]”替换为“ {”和“}”

最佳答案

如果解析此逻辑知道{"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];


因此,现在,您的数据可以是:

[
    ["slide0001.html", "Looking Ahead"],
    ["slide0008.html", "Forecast"],
    ["slide0021.html", "Summary"]
]


如果您的解析逻辑事先不了解数据的结构,则可以添加一些元数据来描述它。例如:

{ meta: { keys: [ "key", "value" ] },
  data: [
    ["slide0001.html", "Looking Ahead"],
    ["slide0008.html", "Forecast"],
    ["slide0021.html", "Summary"]
  ]
}


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

关于json - 将键值数组存储到紧凑的JSON字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6397990/

相关文章:

javascript - 如何使用 node-json2html 将 json 显示为 html?

Haskell:将 (a, b) 键值对列表(可能有重复的键)转换为按键分组的 (a, [b]) 列表

java - 如何将字符串拆分为映射,使用流按重复键对值进行分组?

javascript - 对数据键的值调用方法?

c++ - 基于图形(键/值)数据库的面向性能的设计

google-app-engine - 是否有一个 nosql 存储也允许存储实体之间的关系?

java - JsonObject 抛出 com.google.gson.stream.MalformedJsonException

php - 带有特殊字符的 Json_decode

javascript - 如何分配返回数据对象以便在 View 中呈现它(node.js)

Java Kafka 对象序列化器和反序列化器