¿Cómo concateno dentro de un objeto JSON?

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"]}'

Algo como:

@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?

preguntado el 26 de septiembre de 13 a las 23:09

3 Respuestas

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

Un ejemplo más simple:

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"] })

Respondido el 26 de Septiembre de 13 a las 23:09

¡Gracias por su rápida respuesta! - Josh

Absolutely. Do not think you can just use #{var} and get the right thing out. If anything you should be using #{var.to_json} if you have a JSON library that does that, like within Rails. - tadman

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.

Respondido el 27 de Septiembre de 13 a las 00:09

suspiro 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.

Respondido el 26 de Septiembre de 13 a las 23:09

Don't manipulate JSON like that. Use the JSON class to generate it for you. - el hombre de hojalata

You could avoid a lot of this escaping mess by using something like %Q<...> so that your quotation marks don't need to be escaped each time. %Q puede utilizar {} or [] but since JSON uses both of these, angle brackets are probably the safest. - tadman

Don't hand code JSON. Use JSON.generate(). You will save yourself a lot of headaches. - Michael Geary

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.