finding json errors with ruby

2020-07-24 04:25发布

问题:

i am using ruby gems json_pure and when i get parsing errors i am not able to determine the line number where the error is occuring. i was expecting to find a validator written in ruby that would tell me the line number. what is the best ruby approach to finding the json errors quickly?

thanks!

回答1:

You could try Kwalify: http://www.kuwata-lab.com/kwalify/ruby/users-guide.html

It's not just a JSON/YAML validator, but you give it a schema and it validates against that.

You could use that to verify that your config file is correct (as per your definition of "correct") as well as correct JSON (or YAML), and it will tell you what line number the error happened on, and a bit of context for the error as well.

I removed a ']' from a sample in their documentation and the error message it gave me was

ERROR: document12a.json:10:1 [/favorite] flow sequence is not closed by ']'.

It also does data binding class generation if you want. It seems like a pretty good configuration management/validation tool.



回答2:

You might find it easier to use http://www.jsonlint.com/ to check the JSON is valid - it will highlight any problematic lines.



回答3:

It's and old question, but it's still an issue in current Ruby.

Default JSON parser in Ruby does not tell you the line number and/or column number the parse error occured. Just 'parse' error and that's it.

You could change the parser to Oj and use with MultiJson gem. Oj is great, it's very fast, and it will show the line and even the column number the parsing errors occured! Great.

Sample error for one-line very big JSON (170KB+), Oj will give column 102421.

.../adapters/oj.rb:15:in `load': unexpected character at line 1, column 102421 [parse.c:666] (MultiJson::ParseError)


回答4:

JSON is supposed to be sent over the network as a string, so there's actually only one line.