Close
    Search Search

    Module : JSON

      Module : JSON

      La documentation pour ce module peut être créée sur Module:JSON/doc


      -- -- json.lua -- -- Copyright (c) 2018 rxi -- -- L'autorisation est par la présente accordée, gratuitement, à toute personne obtenant une copie de -- ce logiciel et les fichiers de documentation associés (le "Logiciel" ), de traiter -- le Logiciel sans restriction, y compris, sans limitation, les droits -- d'utiliser, de copier, de modifier, de fusionner, de publier, de distribuer, de sous-licencier et/ou de vendre des copies -- du Logiciel, et d'autoriser les personnes à à qui le Logiciel est fourni -- sous réserve des conditions suivantes : -- -- L'avis de droit d'auteur ci-dessus et cet avis d'autorisation doivent être inclus dans toutes -- les copies ou parties substantielles du Logiciel. -- -- LE LOGICIEL EST FOURNI « EN L'ÉTAT », SANS GARANTIE D'AUCUNE SORTE, EXPRESSE OU -- IMPLICITE, Y COMPRIS MAIS SANS S'Y LIMITER LES GARANTIES DE QUALITÉ MARCHANDE, -- D'ADAPTATION À UN USAGE PARTICULIER ET D'ABSENCE DE CONTREFAÇON. EN AUCUN CAS LES - AUTEURS OU TITULAIRES DE DROITS D'AUTEUR NE SONT TENUS RESPONSABLES DE TOUTE RÉCLAMATION, DOMMAGES OU AUTRE - RESPONSABILITÉ, QUE CE SOIT DANS UNE ACTION CONTRACTUELLE, DÉLICTUELLE OU AUTRE, DÉCOULANT DE, - DE OU EN RELATION AVEC LE LOGICIEL OU LA UTILISATION OU AUTRES TRANSACTIONS DANS LE -- LOGICIEL. -- json local = { _version = "0.1.1" } ------------------------------------ ------------------------------------------- -- Encoder ---- -------------------------------------------------- ------------------------- encodage local local escape_char_map = { [ "" ] = "\", [ """ ] = " "", [ "b" ] = "b", [ "f" ] = "f", [ "n" ] = "n", [ "r" ] = "r", [ "t " ] = "t", } local escape_char_map_inv = { [ "/" ] = "/" } pour k, v par paires (escape_char_map) do escape_char_map_inv[v] = k end fonction locale escape_char(c) return escape_char_map[ c] ou string.format("u%04x", c:byte()) end local function encode_nil(val) return "null" end local function encode_table(val, stack) local res = {} stack = stack ou { } -- Référence circulaire? if stack[val] then error("circular reference") end stack[val] = true if val[1] ~= nil ou next(val) == nil then -- Traiter comme un tableau -- vérifier que les clés sont valides et il n'est pas clairsemé local n = 0 pour k par paires(val) do if type(k) ~= "nombre" then error("table invalide : types de clés mixtes ou invalides") end n = n + 1 end if n ~= #val then error("table non valide : tableau clairsemé") end -- Encoder pour i, v in ipairs(val) do table.insert(res, encode(v, stack)) end stack[val] = nil return "[ " .. table.concat(res, ",") .. "]" else -- Traiter comme un objet pour k, v par paires(val) do if type(k) ~= "string" then error("table invalide : types de clés mixtes ou invalides") end table.insert(res , encoder(k, pile) .. ":".. encode(v, stack)) end stack[val] = nil return "{" .. table.concat(res, ",") .. "}" end end fonction locale encode_string(val) return '"' .. val:gsub('[%z1-31"]', escape_char) .. '"' end local function encode_number(val) -- Vérifiez NaN, -inf et inf if val ~= val ou val <= -math.huge ou val >= math.huge then error("unexpected number value '" . . tostring(val) .. "'") end return string.format("%.14g", val) end local type_func_map = { [ "nil" ] = encode_nil, [ "table" ] = encode_table, [ "string" ] = encode_string, [ "number " ] = encode_number, [ "boolean" ] = tostring, } encode = function(val, stack) local t = type(val) local f = type_func_map[t] if f then return f(val, stack) end error(" type inattendu '" .. t .. "'") end function json.encode(val) return ( encode(val) ) end ------------------------------ ------------------------------------------------- - - Décoder ------------------------------------------------ ------------------------------- analyse locale fonction locale create_set(...) local res = {} pour i = 1 , select("#", ...) do res[ select(i, ...) ] = true end return res end local space_chars = create_set(" ", "t", "r", "n") local delim_chars = create_set(" ", "t", "r", "n", "]", "}", ",") local escape_chars = create_set("", "/", '"', "b ", "f", "n", "r", "t", "u") littéraux locaux = create_set("true", "false", "null") local literal_map = { [ "true" ] = true , [ "false" ] = false, [ "null" ] = nil, } fonction locale next_char(str, idx, set, negate) for i = idx, #str do if set[str:sub(i, i)] ~= annuler puis retourner i end end return #str + 1 end fonction locale decode_error(str, idx, msg) local line_count = 1 local col_count = 1 pour i = 1, idx - 1 do col_count = col_count + 1 if str:sub (i, i) == "n" le n line_count = line_count + 1 col_count = 1 end end error( string.format("%s at line %d col %d", msg, line_count, col_count) ) end local function codepoint_to_utf8(n) -- http://scripts .sil.org/cms/scripts/page.php?site_id=nrsi&id=iws-appendixa local f = math.floor if n <= 0x7f then return string.char(n) elseif n <= 0x7ff then return string.char( f(n / 64) + 192, n % 64 + 128) elseif n <= 0xffff alors retourne string.char(f(n / 4096) + 224, f(n % 4096 / 64) + 128, n % 64 + 128) elseif n <= 0x10ffff then return string.char(f(n / 262144) + 240, f(n % 262144 / 4096) + 128, f(n % 4096 / 64) + 128, n % 64 + 128) end error( string.format("invalid unicode codepoint '%x'", n) ) end local function parse_unicode_escape(s) local n1 = tonumber( s:sub(3, 6), 16 ) local n2 = tonumber( s: sub(9, 12), 16 ) -- Paire de substitution ? if n2 alors retourne codepoint_to_utf8((n1 - 0xd800) * 0x400 + (n2 - 0xdc00) + 0x10000) else retourne codepoint_to_utf8(n1) end end local function parse_string(str, i) local has_unicode_escape = false local has_surrogate_escape = false local has_escape = false local has_escape local last for j = i + 1, #str do local x = str:byte(j) if x < 32 then decode_error(str, j, "control character in string") end if last == 92 then -- " " (caractère d'échappement) if x == 117 then -- "u" (séquence d'échappement unicode) hex local = str:sub(j + 1, j + 5) sinon hex:find("%x%x%x% x") then decode_error(str, j, "échappement unicode non valide dans la chaîne") end if hex:find("^[dD][89aAbB]") then has_surrogate_escape = true else has_unicode_escape = true end else local c = string.char (x) sinon escape_chars[c] alors decode_error(str, j, "caractère d'échappement invalide '" .. c .. "' dans la chaîne") end has_escape = true end last = nil elseif x == 34 then -- '"' (fin de la chaîne) local s = str:sub(i + 1, j - 1) if has_surrogate_escape then s = s:gsub("u[dD][89aAbB]..u....", parse_unicode_escape) end if has_unicode_escape then s = s:gsub("u....", parse_unicode_escape) end if has_escape then s = s:gsub(".", escape_char_map_inv) end return s, j + 1 else last = x end end decode_error(str, i, "devis de fermeture attendu pour la chaîne") end local function parse_number(str, i) local x = next_char(str, i, delim_chars) local s = str:sub(i, x - 1) local n = tonumber(s) sinon n alors decode_error(str, i, "nombre invalide '" .. s .. "'") end return n, x end local function parse_literal(str, i) local x = next_char(str, i, delim_chars) local word = str:sub(i, x - 1) sinon literals[word] alors decode_error (str, i, "littéral invalide '" .. mot .. "'") end return literal_map[word], x end local function parse_array(str, i) local res = {} local n = 1 i = i + 1 while 1 do local xi = next_char(str, i, space_chars, true ) -- Vide / fin de tableau ? if str:sub(i, i) == "]" then i = i + 1 break end -- Lire le jeton x, i = analyser(str, i) res[n] = xn = n + 1 -- Jeton suivant i = next_char(str, i, space_chars, true) local chr = str:sub(i, i) i = i + 1 if chr == "]" then break end if chr ~= "," then decode_error(str, i, "attendu ']' ou ','") end end return res, i end local function parse_object(str, i) local res = {} i = i + 1 while 1 do local key, val i = next_char(str , i, space_chars, true) -- Vide/fin de l'objet ? if str:sub(i, i) == "}" then i = i + 1 break end -- Touche de lecture if str:sub(i, i) ~= '"' then decode_error(str, i, "chaîne attendue for key") clé de fin, i = parse(str, i) -- Read ':' delimiter i = next_char(str, i, space_chars, true) if str:sub(i, i) ~= ":" then decode_error (str, i, "attendu ':' après la clé") end i = next_char(str, i + 1, space_chars, true) -- Lire la valeur val, i = parse(str, i) -- Définir res[key] = val -- Jeton suivant i = next_char(str, i, space_chars, true) local chr = str:sub(i, i) i = i + 1 if chr == "}" then break end if chr ~= ", " then decode_error(str, i, "attendu '}' ou ','") end end return res, i end local char_func_map = { [ '"' ] = parse_string, [ "0" ] = parse_number, [ "1" ] = parse_number, [ "2" ] = parse_number, [ "3" ] = parse_number, [ "4" ] = parse_number, [ "5" ] = parse_number, [ "6" ] = parse_number, [ "7" ] = parse_number, [ "8" ] = parse_number, [ "9" ] = parse_number, [ "-" ] = parse_number, [ "t" ] = parse_literal, [ "f" ] = parse_literal, [ "n" ] = parse_l iteral, [ "[" ] = parse_array, [ "{" ] = parse_object, } parse = function(str, idx) local chr = str:sub(idx, idx) local f = char_func_map[chr] if f then return f (str, idx) end decode_error(str, idx, "caractère inattendu '" .. chr.. "'") end function json.decode(str) if type(str) ~= "string" then error("argument attendu de type string, got " ..


      ajouter un commentaire de Module : JSON
      Commentaire envoyé avec succès ! Nous l'examinerons dans les prochaines heures.

      End of content

      No more pages to load