Josh
Josh

Reputation: 490

How do I concatenate within a JSON object?

I created a variable in Ruby:

@var = 5

Now I would like to use that variable in this object:

@json = '{"id":0,"observation": [{"key": "BLAH_BLAH","value": ["SOMETHING"]}'

Something like:

@json = '{"id":#{@var},"observation": [{"key": "BLAH_BLAH","value": ["SOMETHING"]}'

When I remove the double quotes from within the object and replace them with single quotes then wrap the JSON object in double quotes I receive a parsing error. When I try to escape the quotes with \ I also get a parsing error:

@json = "{\"id\":\"#{@var}\",\"observation\": [{\"key\": \"BLAH_BLAH\",\"value\": [\"SOMETHING\"]}"

Might there be another way to go about this?

Upvotes: 0

Views: 1800

Answers (3)

the Tin Man
the Tin Man

Reputation: 160551

Use the JSON class to manipulate JSON strings:

require 'json'

json = '{"id":0,"observation":[{"key":"BLAH_BLAH","value":["SOMETHING"]}]}'

foo = JSON[json]  # => {"id"=>0, "observation"=>[{"key"=>"BLAH_BLAH", "value"=>["SOMETHING"]}]}
foo['id'] = 5
puts JSON[foo]

# >> {"id":5,"observation":[{"key":"BLAH_BLAH","value":["SOMETHING"]}]}

There are lots of special things that can happen when dealing with unknown structures and objects, that interpolation into a string won't cover. You should take advantage of the pre-built wheels and not try to invent or circumvent using them.

Upvotes: 0

Josh
Josh

Reputation: 490

sigh after being frustrated for countless minutes I found the solution to be:

"{\"id\":#{@u_id},\"observation\": [{\"key\": \"ACCOUNT_CLOSED\",\"value\": [\"N\"]}

I hate it when its something so simple.

Upvotes: -1

Ryan Bigg
Ryan Bigg

Reputation: 107718

This is happening because you're using single quotes to build the JSON string, and inside single quotes in Ruby, interpolation does not happen.

A simpler example:

a = 1
puts '#{a}'
puts "#{a}"

I would really recommend using a library to build your JSON, such as the built-in JSON module within Ruby.

require 'json'
JSON.generate(:id => @var, :observation => { :key => "blah blah", :value => ["something"] })

Upvotes: 4

Related Questions