Re: Euphoria JSON parser

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

Don't know if this can fit your need but there is a JSON to Euphoria sequence converter in my Eu4 Standard library (v0.8.3 uploaded today).

It could be extracted with only needed dependancies. Here is the code:

 
include std/convert.e 
include std/search.e 
include std/text.e 
include _types_.e 
include _conv_.e 
include _sequence_.e 
include _debug_.e 
include _file_.e 
 
function find_matching(integer c, sequence s, integer from) 
  integer n, e 
 
  if c = '(' then 
    e = ')' 
  elsif c = '[' then 
    e = ']' 
  elsif c = '{' then 
    e = '}' 
  elsif c = '<' then 
    e = '>' 
  elsif c = '"' then 
    e = '"' 
  elsif c = 39 then 
    e = 39 
  end if 
 
  n = 0 
  for i = from to length(s) do 
    if s[i] = c then n += 1 end if 
    if s[i] = e then n -= 1 end if 
    if n = -1 then return i end if 
  end for 
  return 0 
end function 
 
function split_list(sequence json, integer sep) 
  sequence result 
  integer c, e, previous 
 
  c = 1 
  result = {} 
  previous = 1 
  while c < length(json) do 
    if (json[c] = '{') or (json[c] = '[') then 
      e = find_matching(json[c], json, c+1) 
      c = e 
    elsif json[c] = sep then 
      result = append(result, trim(json[previous..c-1])) 
      c += 1 
      previous = c 
    end if 
    c += 1 
  end while 
  result = append(result, trim(json[previous..$])) 
  return result 
end function 
 
global function json_to_sequence(sequence json) 
  sequence s, t 
  object result 
 
  result = {} 
  if length(json) = 0 then return result end if 
  if (json[1] = '{') and (json[$] = '}') then 
    s = split_list(json[2..$-1], ',') 
    for i = 1 to length(s) do 
      t = split_list(s[i], ':') 
      if length(t) != 2 then 
        error_message("missing colon!", 1) 
      end if 
      if not begins("\"", t[1]) or not ends("\"", t[1]) then 
        error_message("missing string!", 1) 
      end if 
      result = append(result, {dequote(t[1], {}), json_to_sequence(t[2])}) 
    end for 
  elsif (json[1] = '[') and (json[$] = ']') then 
    s = split_list(json[2..$-1], ',') 
    for i = 1 to length(s) do 
      if length(s[i]) then 
        result = append(result, json_to_sequence(s[i])) 
      end if 
    end for 
  elsif is_number(json) then 
    result = to_number(json) 
  elsif is_string(json) then 
    result = dequote(json, {}) 
  end if 
  return result 
end function 
 

Jean-Marc

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

Search



Quick Links

User menu

Not signed in.

Misc Menu