SafeParse
Parse json safely
Installation
Add this line to your application's Gemfile:
gem 'safe_parse'
And then execute:
$ bundle
Or install it yourself as:
$ gem install safe_parse
Usage
Parsing a json string safely.
irb> json_string = JSON.generate({abc: 123})
=> "{\"abc\":123}"
irb> SafeParse.call(json_string)
=> {"abc"=>123}
Parsing an invalid json string will default to {}
.
irb> invalid_json_string = "abc123"
=> "abc123"
irb> SafeParse.call(invalid_json_string)
=> {}
SafeParse can take a default to return if the json parsing fails.
irb> SafeParse.call(invalid_json_string, {abc: 123})
=> {:abc=>123}
Safe parse can also take a ruby hash and it correctly.
irb> SafeParse.call({ruby: "hash"})
=> {:ruby=>"hash"}
Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/gogogarrett/safe_parse. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.