json - Uncover object type after it has been converted to string -


i have rather peculiar issue need workaround, in ruby.

i receive list of values, say:

["foo", "0.0", "1", "{}", "[]"] 

i want uncover actual type of each element, having no power on fact has been converted string type.

my initial attempt load each value individually using json deserialization, e.g.:

my_list.each |element|   puts json.load(element).class end 

however has various caveats mean doesn't work quite right.

e.g. json.load("0.0").class give me float, json.load("foo").class will, of course, bomb out. solution use try/catch or rescue block when actual string, it's not reliable breaks custom classes (say said s = someclass.new, json.load("s") rescues string) , ends rather ugly code.

my_list.each |element|   puts json.load(element).class rescue string end 

alas, question have ask is, there exist way "unconvert" string , find out object type of whatever contained within string?

apologies if issue has been answered, have searched @ great length, , no avail. right now, feel answer "no".

thanks help!

if values json strings, eval fail. use json.parse:

['foo', "0.0", "1", "{}", "[]"].map {|a| json.parse(a, quirks_mode: true) rescue } # => ["foo", 0.0, 1, {}, []] 

the :quirks_mode option enables parsing of single values, e.g. 0.0 , 1 (thanks stefan).

it's bad idea use rescue without specifying error class, though, better:

['foo', "0.0", "1", "{}", "[]"].map |val|   begin     json.parse(val, quirks_mode: true)   rescue json::parsererror     val   end end # => ["foo", 0.0, 1, {}, []] 

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -