我正在尝试将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中实现这一目标?谢谢!
答案 0 :(得分:3)
使用json gem,您可以解析文件的内容,将新哈希添加到数组并将其重新编码为JSON以重写文件。