JSON

JSON 知识量:10 - 17 - 48

10.1 JSON用于配置文件><

作为配置文件的JSON- 10.1.1 -

软件中经常会有配置文件,它让我们可以不必重新编译就能修改设置。配置文件的格式有很多种,例如:ini、xml和json等。下面是这三种格式的比较:

ini格式如下:

[general]
playIntro=false
mouseSensitivity=0.54
[display]
complexTextures=ture
brightness=4.2
widgetsPerFrame=326
mode=windowed
[sound]
volume=1
effects=0.68

xml格式如下:

<?xml version="1.0" encoding="UTF-8"?>
<settings>
    <general>
        <playIntro>false</playIntro>
        <mouseSensitivity>0.54</mouseSensitivity>
    </general>
    <display>
        <complexTextures>ture</complexTextures>
        <brightness>4.2</brightness>
        <widgetsPerFrame>326</widgetsPerFrame>
        <mode>windowed</mode>
    </display>
    <sound>
        <volume>1</volume>
        <effects>0.68</effects>
    </sound>
</settings>

json格式如下:

{
    "general": {
        "playIntro": false,
        "mouseSensitivity": 0.54
    },
    "display": {
        "complexTextures": true,
        "brightness": 4.2,
        "widgetsPerFrame": 326,
        "mode": "windowed"
    },
    "sound": {
        "volume": 1,
        "effects": 0.68
    }
}

以上三种格式都有很好的可读性,如果要修改某一项,例如:声音,可以快速定位修改。这就是配置文件的优势。

但是每种格式都由优缺点:ini格式没有xml那些大于号和小于号以及json格式的花括号,可读性最佳,但是ini格式不能很好的表示更复杂的信息,例如嵌套信息或复杂的列表。xml能够包含更复杂的信息,但是不像json一样具有数据类型。

实践中,决定使用哪种数据类型作为配置文件,除了格式本身的特点外,系统的支持情况也是重要的因素,因此,应当综合考虑,选择最优方案。