0

The docs say this:

{ :name => "Konata Izumi", 'age' => 16, 1 => 2 }.to_json
=> {"name": "Konata Izumi", "1": 2, "age": 16}

But when I actually try it in the rails console it looks like this:

{ :name => "Konata Izumi", 'age' => 16, 1 => 2 }.to_json
=> "{\"name\":\"Konata Izumi\",\"age\":16,\"1\":2}"

How do I get it to return an object/hash instead of a string? I don't want the outer quotes around the curly braces. I want {...} instead of "{...}".

4
  • Well, then don't convert it to JSON then? { :name => "Konata Izumi", 'age' => 16, 1 => 2 } this is already a hash, no need to do to_json. Commented Jun 22, 2020 at 19:06
  • But I need the JSON format to make a POST request, this value would be in the body of the POST request. Commented Jun 22, 2020 at 19:17
  • 1
    The outer quotes are not actually in the result JSON value, that's just the console letting you know that it's printing a string. Commented Jun 22, 2020 at 19:23
  • A string is of course an object. You may wish to change the wording of your title and text. Commented Jun 22, 2020 at 23:03

2 Answers 2

3
irb(main):012:0> x = { :name => "Konata Izumi", 'age' => 16, 1 => 2 }.to_json
irb(main):013:0> puts x
{"name":"Konata Izumi","age":16,"1":2}
=> nil

If you capture the results in a variable and then print it, you'll see that it is working as expected. The quotes are just the console's way of indicating that the stuff after => is a string.

Sign up to request clarification or add additional context in comments.

Comments

1

JSON is a format for serializing data to text. It simply is a String, it cannot be anything else, that would be non-sensical.

If you want to keep a Ruby object instead of serializing to a string, simply don't serialize to a string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.