ritz078 / transform

A polyglot web converter.
https://transform.tools
MIT License
8k stars 587 forks source link

ruby hash to JSON converter #81

Closed ritz078 closed 4 years ago

p-racoon commented 5 years ago

JSON and Ruby Hashes are pretty similar, but still, have their differences. One of them being that Ruby hashes allow Objects as keys, whereas JSON does not. Example:-

Ruby:
{
    {'a'=>1} => 2
}

This is a valid Ruby hash, but JSON does not allow that. hence, in this case, we can either call this as invalid input for JSON conversion, or we can do what to_JSON() function does in ruby. So basically it would simply Stringify the object there is, and return

{
    "{\"a\"=>1}" : 2
}

(As shown in gif) RubyHashToJSON

Read more about to_json() [here] (https://apidock.com/rails/Hash/to_json) Try it yourself here Remember to use require 'json'

p-racoon commented 5 years ago

The JSON syntax or Definition in some sense can be found here

p-racoon commented 5 years ago

One more such issue is use and support of symbols in Ruby. In Ruby, Symbols can be used as keys

{
    :a => 65   # a here is the symbol
}

This too is a valid Ruby hash, but JSON does not allow that. Hence, in this case as well, we can either call this as invalid input for JSON conversion, or we can do what to_JSON() function does in ruby.

{
    "a" : 65
}

RubyHashToJSONSymbolsAsKey Ref: https://docs.ruby-lang.org/en/2.3.0/Hash.html Try it [here] (https://www.tutorialspoint.com/execute_ruby_online.php)

Edit: (Just some extra Clarification.) Javascript supports the use of Symbols in but they are difficult to be used with Object Literals. Because Ideally for Javascript that should have converted into

{
    [Symbol("a")] : 65 
}

But then this would become inaccessible, Since Symbol("a") == Symbol("a") //returns false in javascript. Hence for different Keys, same value can't be expected. Besides, JS objects are different from JSON Cick Here to see the definition of JSON. It doesn't mention Symbols.

ritz078 commented 5 years ago

We should do what to_JSON() does in all cases.

p-racoon commented 5 years ago

I found this library named Opal should we use this or stick to building a compiler?

ritz078 commented 5 years ago

you can use 3rd party libraries if they work

stale[bot] commented 4 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.