How to convert a ruby hash object to JSON?

前端 未结 5 629
清酒与你
清酒与你 2020-11-29 15:14

How to convert a ruby hash object to JSON? So I am trying this example below & it doesn\'t work?

I was looking at the RubyDoc and obviously Hash obj

相关标签:
5条回答
  • 2020-11-29 15:53

    You should include json in your file

    For Example,

    require 'json'
    
    your_hash = {one: "1", two: "2"}
    your_hash.to_json
    

    For more knowledge about json you can visit below link. Json Learning

    0 讨论(0)
  • 2020-11-29 15:55

    Add the following line on the top of your file

    require 'json'
    

    Then you can use:

    car = {:make => "bmw", :year => "2003"}
    car.to_json
    

    Alternatively, you can use:

    JSON.generate({:make => "bmw", :year => "2003"})
    
    0 讨论(0)
  • 2020-11-29 16:00
    require 'json/ext' # to use the C based extension instead of json/pure
    
    puts {hash: 123}.to_json
    
    0 讨论(0)
  • 2020-11-29 16:02

    You can also use JSON.generate:

    require 'json'
    
    JSON.generate({ foo: "bar" })
    => "{\"foo\":\"bar\"}"
    

    Or its alias, JSON.unparse:

    require 'json'
    
    JSON.unparse({ foo: "bar" })
    => "{\"foo\":\"bar\"}"
    
    0 讨论(0)
  • 2020-11-29 16:14

    One of the numerous niceties of Ruby is the possibility to extend existing classes with your own methods. That's called "class reopening" or monkey-patching (the meaning of the latter can vary, though).

    So, take a look here:

    car = {:make => "bmw", :year => "2003"}
    # => {:make=>"bmw", :year=>"2003"}
    car.to_json
    # NoMethodError: undefined method `to_json' for {:make=>"bmw", :year=>"2003"}:Hash
    #   from (irb):11
    #   from /usr/bin/irb:12:in `<main>'
    require 'json'
    # => true
    car.to_json
    # => "{"make":"bmw","year":"2003"}"
    

    As you can see, requiring json has magically brought method to_json to our Hash.

    0 讨论(0)
提交回复
热议问题