Project

jsos

0.0
No commit activity in last 3 years
No release in over 3 years
Convert JSON into nested OpenStruct objects with ease.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 1.10
>= 0
~> 10.0
~> 3.0
~> 0.11
>= 0
 Project Readme

JSOS

Build Status Gem Version

Use Ruby's OpenStruct object to represent JSON strings, making nested data a method call away.

Installation

Add this line to your application's Gemfile:

gem 'jsos'

And then execute:

$ bundle

Or install it yourself as:

$ gem install jsos

Usage

JSOS turns a JSON string into an OpenStruct. It also allows you to construct JSON strings from scratch. Setter methods are turned into JSON keys and their arguments become the values. Getter methods return those values.

# parsing JSON into OpenStruct
jsos = JSOS.new("{\"foo\":\"bar\"}")
jsos.foo
#=> "bar"

# parsing Hash into OpenStruct
jsos = JSOS.new({foo: "bar"})
jsos.foo
#=> "bar"

# creating an empty object and converting to JSON
jsos = JSOS.new
jsos.to_json
#=> "{}"

# adding to the empty JSON
jsos.foo = "bar"
jsos.to_json
#=> "{\"foo\":\"bar\"}"

A missing getter method is created with an empty JSOS object as its value. This allows you to chain methods to created nested JSON strings.

# nesting empty JSON objects
jsos = JSOS.new
jsos.foo
jsos.to_json
#=> "{\"foo\":{}}"

# chaining methods to create nested JSON strings
jsos = JSOS.new
jsos.abc.foo = "bar"
jsos.xyz.foo = "baz"
jsos.to_json
#=> "{\"abc\":{\"foo\":\"bar\"}, \"xyz\":{\"foo\":\"baz\"}}"

You can grab object level keys and values like a normal Ruby Hash. These do not return nested keys/values.

jsos = JSOS.new("{\"abc\":{\"foo\":\"bar\"}, \"xyz\":{\"foo\":\"baz\"}}")
jsos.keys
#=> ["abc", "xyz"]
jsos.values
#=> ["#<JSOS foo=\"bar\">", "#<JSOS foo=\"baz\">"]

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/jdenen/jsos.

License

The gem is available as open source under the terms of the MIT License.