pmerino
pmerino

Reputation: 6130

Append a JSON string to a file which already contains JSON in Ruby

I'm trying to append a JSON string into a file which has already more JSON strings:

[
    {
        "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"
    }
]

I'd need to append strings like {"title":"test","content":"test","date":"2011-12-10 21:35:48 +0100","author":"zad0xsis","id":"0EhQ0"} conserving the JSON format:

[
    {
        "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"}
]

So it looks something like so, in little words, appending it so it's still valid JSON. How can I achieve this in Ruby? Thanks!

Upvotes: 1

Views: 909

Answers (1)

tomferon
tomferon

Reputation: 5001

With the json gem, you could parse the file's content, add the new hash to the array and re-encode it into JSON to rewrite the file.

Upvotes: 3

Related Questions