Re: EuMVC:Map to Json

new topic     » goto parent     » topic index » view thread      » older message » newer message
euphoric said...

@ghaberek, or anybody who knows,

Is there a map_to_json() available in Greg's json lib?

(If not, there should be. grin)

Also, if not, how would I do it?

Thank you!

You're right, there should be, but Euphoria isn't typed strongly enough to make a one-to-one translation from a map to JSON, so some type information has to be specified manually.

I originally did try storing JSON objects as maps but I had no way of reading back value types beyond "atom or sequence" and since maps are just atoms I couldn't tell a regular number from any other JSON type.

This is why I opted to just reference everything with its type as {type,value}. Another snag is that Euphoria maps accept any key, but JSON keys can only be strings, so there are significant limits with trying to convert maps to JSON.

That being said, I just pushed v1.15.0 which includes a new json_import() function just for you (complete with docs). I've posted a simple test program below.

(P.S. this also helped me find a bug in json_print() that would totally screw up numbers by printing them with unnecessary scientific notation!)

include std/map.e 
include std/types.e 
include mvc/json.e 
map color_map = map:new_from_kvpairs({ 
    { "black",   #000000 }, 
    { "maroon",  #800000 }, 
    { "green",   #008000 }, 
    { "olive",   #808000 }, 
    { "navy",    #000080 }, 
    { "purple",  #800080 }, 
    { "teal",    #008080 }, 
    { "silver",  #C0C0C0 }, 
    { "grey",    #808080 }, 
    { "red",     #FF0000 }, 
    { "lime",    #00FF00 }, 
    { "yellow",  #FFFF00 }, 
    { "blue",    #0000FF }, 
    { "fuchsia", #FF00FF }, 
    { "aqua",    #00FFFF }, 
    { "white",   #FFFFFF } 
procedure main() 
    object json = json_import( color_map ) 
    if json[J_TYPE] = JSON_NONE then 
        printf( 2, "%s\n", {json_last_error()} ) 
    end if 
    json_print( 1, json,, TRUE ) 
end procedure 

Output are integers because JSON doesn't support hexadecimal notation.

    "aqua": 65535, 
    "black": 0, 
    "blue": 255, 
    "fuchsia": 16711935, 
    "green": 32768, 
    "grey": 8421504, 
    "lime": 65280, 
    "maroon": 8388608, 
    "navy": 128, 
    "olive": 8421376, 
    "purple": 8388736, 
    "red": 16711680, 
    "silver": 12632256, 
    "teal": 32896, 
    "white": 16777215, 
    "yellow": 16776960 


new topic     » goto parent     » topic index » view thread      » older message » newer message


Quick Links

User menu

Not signed in.

Misc Menu