Search code examples
javascriptjsonrubyruby-hash

Get javascript string out of ruby hash sent in JSON


So, I have a ruby program that takes a hash and turns it into a JSON string (lets say the hash is #FFFFFF) and that JSON string is sent to a javascript program where it needs to get #FFFFFF out of the JSON string, i've tried JSON.parse(); to no avail, and JSON.stringify(); only returns this "{\"color\":\"#FFFFFF\"}" how do I get it to return just #FFFFFF in a javascript string?


Solution

  • The fact that the JSON originates from a Ruby hash is irrelevant. You have to JSON.parse the JSON string — but! then you also have to access the .color property of the resulting object

    let json = '{"color":"#FFFFFF"}'
    let data = JSON.parse(json)
    console.log(data.color)
    // #FFFFFF