X
X
xSenelegx2014-01-31 06:25:22
ruby
xSenelegx, 2014-01-31 06:25:22

Unexpected token at '' when using JSON in ruby?

Ruby 2.0
json (1.8.1, 1.7.7)
A function that adds an object to a json file:

def add(input_hash)
    f = File.open('db.dat','a+')
    f.write(JSON.generate(input_hash))
    f.close
end

A function that reads a json object from a file:
def get
    f = File.open('db.dat','a+')
    tmp = JSON.parse(f.read)
    return tmp
end

If you insert one value into the file, any json object, then reading a single object occurs without problems.
If another json object is inserted into the same file, then, in fact, an error occurs when parsing the second value - 'Unexpected token at <2jsonobject>'

/var/lib/gems/2.0.0/gems/json-1.8.1/lib/json/common.rb:178:in `parse': 757: unexpected token at '{"mail":{"google": "password"}}' (JSON::ParserError)

1. I tried to read and write lines with the strip method
2. I tried to put objects into the array, like -
>> JSON.parse([ 'foo' ].to_json).first
=> "foo"

and
>> json = 'foo'.to_json
>> JSON.parse(json, :quirks_mode => true)
=> "foo"

Tell me what I'm doing wrong.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Burov, 2014-01-31
@xSenelegx

If you write two json objects one after another, you get invalid json, see the contents of the file.
f = File.open('db.dat','a+'); here it is more logical to use 'r'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question