将JSON字符串附加到已在Ruby中包含JSON的文件中

时间:2011-12-10 20:41:05

标签: ruby json formatting append

我正在尝试将JSON字符串附加到已有更多JSON字符串的文件中:

[
    {
        "title": "A test title",
        "content": "A test content",
        "date": "10/01/10",
        "author": "zad0xsis",
        "id": "vnMiP"
    },
    {
        "title": "A test title",
        "content": "A test content",
        "date": "10/01/10",
        "author": "zad0xsis",
        "id": "vnZiP"
    },
    {
        "title": "A test title",
        "content": "A test content",
        "date": "10/01/10",
        "author": "zad0xsis",
        "id": "vnAiP"
    }
]

我需要追加保存JSON格式的{"title":"test","content":"test","date":"2011-12-10 21:35:48 +0100","author":"zad0xsis","id":"0EhQ0"}字符串:

[
    {
        "title": "A test title",
        "content": "A test content",
        "date": "10/01/10",
        "author": "zad0xsis",
        "id": "vnMiP"
    },
    {
        "title": "A test title",
        "content": "A test content",
        "date": "10/01/10",
        "author": "zad0xsis",
        "id": "vnZiP"
    },
    {
        "title": "A test title",
        "content": "A test content",
        "date": "10/01/10",
        "author": "zad0xsis",
        "id": "vnAiP"
    },
    {"title":"test","content":"test","date":"2011-12-10 21:35:48 +0100","author":"zad0xsis","id":"0EhQ0"}
]

所以它看起来像这样,用小词,附加它所以它仍然是有效的JSON。我怎样才能在Ruby中实现这一目标?谢谢!

1 个答案:

答案 0 :(得分:3)

使用json gem,您可以解析文件的内容,将新哈希添加到数组并将其重新编码为JSON以重写文件。