Skip to content

回复:JSON-RPC 密码 ​

原始发布页

打开来源页面
查看 1 个交叉存档

我研究了一下配置文件格式,下面是对比。

YAML 太庞大了。我不确定是否有轻量、易于构建的库可供我们集成到项目中。似乎有些杀鸡用牛刀。

JSON 很诱人,我也倾向于喜欢它,但有两个主要症结:

  1. 没有注释!配置文件里不能通过注释掉一行来禁用它,这怎么行?
  2. 对用户不太友好,所有字符串(包括键)都必须加“引号”,还必须记得在行末加逗号。 { "key" : "value", }

我想,我们可以很容易地预处理 JSON:逐行读取配置文件,在任何 # 字符(和/或“//”?)处截断该行,把各行拼接成一个字符串再交给 JSON,这样就可以写成: # comment "key" : "value", # still have to remember the comma "key2" : "value", // comment like this or both

Boost 有 boost::program_options。

我们可以自行读取各行,并把它们放入 map<string, string> mapConfig。

while (!eof) 读取一行 如果找到 '#',截断该行 在第一个 ':' 处分割 -> key, value mapConfig.insert(key, value)

如果使用这种语法: # 注释 key : value

……并且不允许在键前使用空白缩进,我想我们就是 YAML 的一个子集;如果以后需要更高的复杂度,可以再切换到 YAML。

选择自行解析并不意味着我们不能按需对特定参数值使用 JSON。如果某个选项需要列表或更结构化的数据,随时可以把它的值作为 json 解析: key : ["item1", "item2", "item3"]

不过那样它就必须全写在一行里。

我想我倾向于自行解析的 mapConfig: # 注释 key : value

英文原文 ​

展开英文原文

I was researching config file formats, here's a comparison.

YAML is massive. I'm not sure there's a lightweight easy to build library we can integrate into our project. Seems overkill.

JSON is tempting and I'm inclined to like it, but two main sticking points:

  1. No comments! How can you have a config file where you can't comment out a line to disable it?
  2. Not very user friendly to have to "quote" all the strings, including the keys, and also have to remember the comma at the end of lines. { "key" : "value", }

I suppose we could easily preprocess JSON reading the config file one line at a time, truncate the lines at any # character (and/or "//"?), concatenate them into a string and pass it to JSON, so you could go: # comment "key" : "value", # still have to remember the comma "key2" : "value", // comment like this or both

Boost has boost::program_options.

We could read lines ourselves and feed them into a map<string, string> mapConfig.

while (!eof) read line if '#' found, truncate line split line at first ':' -> key, value mapConfig.insert(key, value)

If we use the syntax: # comment key : value

...and don't allow whitespace indenting before the keys, I guess we would be a subset of YAML and could switch to YAML someday if we need more complexity.

If we go with self parsed, that doesn't mean we can't use JSON on particular parameter values as needed. If an option needs a list or more structured data, it could always parse its value as json: key : ["item1", "item2", "item3"]

Although it has to be all on one line then.

I guess I'm leaning towards self parsed mapConfig: # comment key : value

为历史保存,为中文读者整理。每篇档案均附来源与英文原文。