Jump to content
Rpg²S Forum

JSON Encoder/Decoder


Midi
 Share

Recommended Posts

JSON Encoder/Decoder

 

Descrizione

Script di utilità per scripters. Permette di decodificare una stringa JSON in una serie di oggetti, e di codificare determinati oggetti in JSON.

 

Autore

game_guy (modifiche di Midi)

 

Allegati

Nessuno

 

Istruzioni per l'uso

Incollare lo script nella sezione "Materials", sopra il "Main".

I comandi sono JSON.decode(stringa) per decodificare una stringa JSON, e JSON.encode(oggetto) per codificare un oggetto in JSON.

 

Script

 

 

#===============================================================================
# JSON Encoder/Decoder
# Version 1.2
# Author: game_guy
# Mods:   Midi
#-------------------------------------------------------------------------------
# Changelog:
# - v. 1.2:
#    - whitespaces management
#    - decimal number parsing
#-------------------------------------------------------------------------------
# Intro:
# JSON (JavaScript Object Notation) is a lightweight data-interchange 
# format. It is easy for humans to read and write. It is easy for machines to 
# parse and generate.
# This is a simple JSON Parser or Decoder. It'll take JSON thats been 
# formatted into a string and decode it into the proper object.
# This script can also encode certain ruby objects into JSON.
#
# Features:
# Decodes JSON format into ruby strings, arrays, hashes, integers, booleans.
#
# Instructions:
# This is a scripters utility. To decode JSON data, call
# JSON.decode("json string")
# -Depending on "json string", this method can return any of the values:
#  -Integer
#  -Float
#  -String
#  -Boolean
#  -Hash
#  -Array
#  -Nil
#
# To Encode objects, use
# JSON.encode(object)
# -This will return a string with JSON. Object can be any one of the following
#  -Integer
#  -String
#  -Boolean
#  -Hash
#  -Array
#  -Nil
#
# Credits:
# game_guy ~ Creating it.
# Midi ~ Midifyng it :)
#===============================================================================
module JSON
  
  TOKEN_NONE = 0;
  TOKEN_CURLY_OPEN = 1;
  TOKEN_CURLY_CLOSED = 2;
  TOKEN_SQUARED_OPEN = 3;
  TOKEN_SQUARED_CLOSED = 4;
  TOKEN_COLON = 5;
  TOKEN_COMMA = 6;
  TOKEN_STRING = 7;
  TOKEN_NUMBER = 8;
  TOKEN_TRUE = 9;
  TOKEN_FALSE = 10;
  TOKEN_NULL = 11;
  TOKEN_WHITESPACE = 12;
  
  @index = 0
  @json = ""
  @length = 0
  
  def self.decode(json)
    @json = json
    @index = 0
    @length = @json.length
    return self.parse
  end
  
  def self.encode(obj)
    if obj.is_a?(Hash)
      return self.encode_hash(obj)
    elsif obj.is_a?(Array)
      return self.encode_array(obj)
    elsif obj.is_a?(Fixnum) || obj.is_a?(Float)
      return self.encode_integer(obj)
    elsif obj.is_a?(String)
      return self.encode_string(obj)
    elsif obj.is_a?(TrueClass) || obj.is_a?(FalseClass)
      return self.encode_bool(obj)
    elsif obj.is_a?(NilClass)
      return "null"
    end
    return nil
  end
  
  def self.encode_hash(hash)
    string = "{"
    hash.each_key {|key|
      string += "\"#{key}\":" + self.encode(hash[key]).to_s + ","
    }
    string[string.size - 1, 1] = "}"
    return string
  end
  
  def self.encode_array(array)
    string = "["
    array.each {|i|
      string += self.encode(i).to_s + ","
    }
    string[string.size - 1, 1] = "]"
    return string
  end
  
  def self.encode_string(string)
    return "\"#{string}\""
  end
  
  def self.encode_integer(int)
    return int.to_s
  end
  
  def self.encode_bool(bool)
    return (bool.is_a?(TrueClass) ? "true" : "false")
  end
  
  def self.next_token(debug = 0)
    char = @json[@index, 1]
    @index += 1
    case char
    when '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '.' 
      return TOKEN_NUMBER
    when '{' 
      return TOKEN_CURLY_OPEN
    when '}' 
      return TOKEN_CURLY_CLOSED
    when '"' 
      return TOKEN_STRING
    when ',' 
      return TOKEN_COMMA
    when '['
      return TOKEN_SQUARED_OPEN
    when ']'
      return TOKEN_SQUARED_CLOSED
    when ':' 
      return TOKEN_COLON
    when ' ', "\n", "\t"
      return self.next_token(debug)
    end
    @index -= 1
    if @json[@index, 5] == "false"
      @index += 5
      return TOKEN_FALSE
    elsif @json[@index, 4] == "true"
      @index += 4
      return TOKEN_TRUE
    elsif @json[@index, 4] == "null"
      @index += 4
      return TOKEN_NULL
    end
    return TOKEN_NONE
  end
  
  def self.parse(debug = 0)
    complete = false
    while !complete
      if @index >= @length
        break
      end
      token = self.next_token
      case token
      when TOKEN_NONE
        return nil
      when TOKEN_NUMBER
        return self.parse_number
      when TOKEN_CURLY_OPEN
        return self.parse_object
      when TOKEN_STRING
        return self.parse_string
      when TOKEN_SQUARED_OPEN
        return self.parse_array
      when TOKEN_TRUE
        return true
      when TOKEN_FALSE
        return false
      when TOKEN_NULL
        return nil
      end
    end
  end
  
  def self.parse_object
    obj = {}
    complete = false
    while !complete
      token = self.next_token
      if token == TOKEN_CURLY_CLOSED
        complete = true
        break
      elsif token == TOKEN_NONE
        return nil
      elsif token == TOKEN_COMMA
      else
        name = self.parse_string
        return nil if name == nil
        token = self.next_token
        return nil if token != TOKEN_COLON
        value = self.parse
        obj[name] = value
      end
    end
    return obj
  end
  
  def self.parse_string
    complete = false
    string = ""
    while !complete
      break if @index >= @length
      char = @json[@index, 1]
      @index += 1
      case char
      when '"'
        complete = true
        break
      else
        string += char.to_s
      end
    end
    if !complete
      return nil
    end
    return string
  end
  
  def self.parse_number
    @index -= 1
    negative = @json[@index, 1] == "-" ? true : false
    string = ""
    decimal = false
    complete = false
    while !complete
      break if @index >= @length
      char = @json[@index, 1]
      @index += 1
      case char
      when "{", "}", ":", ",", "[", "]"
        @index -= 1
        complete = true
        break
      when "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "."
        raise "Number Format error" if (decimal && char == ".")
        decimal = char == "." unless decimal
        string += char.to_s
      end
    end
    return decimal ? string.to_f : string.to_i
  end
  
  def self.parse_array
    obj = []
    complete = false
    while !complete
      token = self.next_token(1)
      if token == TOKEN_SQUARED_CLOSED
        complete = true
        break
      elsif token == TOKEN_NONE
        return nil
      elsif token == TOKEN_COMMA
      else
        @index -= 1
        value = self.parse
        obj.push(value)
      end
    end
    return obj
  end
  
end 

 

 

 

Bugs e Conflitti Noti

Nessuno

 

Altri dettagli

Lo script funziona anche per XP e VX.

Le istruzioni sono presenti anche all'interno dello script.

Lo script è utilizzabile liberamente.

 

NOTA: lo script non è 100% compatibile con le specifiche JSON.

In particolare:

- non è in grado di leggere e scrivere numerali in notazione esponenziale (quindi per esempio è in grado di leggere il numero 11000 ma non il suo equivalente 1.1E4).

- considera "whitespaces" (e quindi ininfluenti al parsing dei token JSON) solo i caratteri ' ', '\t' e '\n'. Altri caratteri whitespaces causeranno l'interruzione del parsing.

- accetta solo stringhe con codifica UTF-8, altre codifiche potrebbero causare malfunzionamenti.

 

Nonostante queste minime limitazioni, lo script dovrebbe comunque rispondere alla stragrande maggioranza delle esigenze di chi volesse usare JSON.

Edited by Midi

Aurora Dreaming


The Dreamer (v. 1.1) - standalone


72 MB - Il prequel ad Aurora Dreaming



segui il dev-diary ufficiale di Aurora Dreaming!



Bacheca Premi


http://www.rpg2s.net/forum/uploads/monthly_01_2014/post-6-0-39588100-1390575633.png

Link to comment
Share on other sites

Ottimo, è molto utile!

"Io non volevo solo partecipare alle discussioni. Volevo avere il potere di farle fallire" [cit.]

http://holyres.altervista.org/UserBoard/BannerOverdrive35.png
http://holyres.altervista.org/UserBoard/Cap3.png

http://www.indiexpo.net/signature/578.png

Miei script per RPG Maker VX Ace:


*NB Tutti i miei script sono protetti da licenza CC - BY http://i.creativecommons.org/l/by/3.0/88x31.png

Questa licenza permette a terzi di distribuire, modificare, ottimizzare ed utilizzare la tua opera come base, anche commercialmente, fino a che ti diano il credito per la creazione originale. Questa è la più accomodante delle licenze offerte. É raccomandata per la diffusione e l'uso massimo di materiali coperti da licenza.

 

 



I miei tutorial:


Come distribuire il gioco - e anche come creare un'installazione professionale!
RGSS in pillole - Guida completa e facile all'RGSS2 e RGSS3 per novizi ed esperti
Come mappare con VX (e VX Ace) - guida base all'uso degli strumenti del mapping
Loop delle musiche - come tagliarle in modo da far venire musiche continue senza interruzioni finali
Creare backup dei progetti - per evitare di uccidervi dopo un errore che ha fatto perdere tutto!

Link to comment
Share on other sites

JSON! ^ ^

 

 

Script di utilità per scripters.

D:

 

Alla fine note minime, bello vedere uno script così pure per rpg maker! XD Bel lavoro.

^ ^

(\_/)
(^ ^) <----coniglietto rosso, me!
(> <)


Il mio Tumblr dove seguire i miei progetti, i progetti della Reverie : : Project ^ ^

http://i.imgur.com/KdUDtQt.png disponibile su Google Play, qui i dettagli! ^ ^

http://i.imgur.com/FwnGMI3.png completo! Giocabile online, qui i dettagli! ^ ^

REVERIE : : RENDEZVOUS (In allenamento per apprendere le buone arti prima di cominciarlo per bene ^ ^) Trovate i dettagli qui insieme alla mia intervista (non utilizzerò più rpgmaker) ^ ^

 

SUWOnzB.jpg 🖤
http://www.rpg2s.net/dax_games/r2s_regali2s.png E:3 http://www.rpg2s.net/dax_games/xmas/gifnatale123.gif
http://i.imgur.com/FfvHCGG.png by Testament (notare dettaglio in basso a destra)! E:3
http://i.imgur.com/MpaUphY.jpg by Idriu E:3

Membro Onorario, Ambasciatore dei Coniglietti (Membro n.44)

http://i.imgur.com/PgUqHPm.png
Ufficiale
"Ad opera della sua onestà e del suo completo appoggio alla causa dei Panda, Guardian Of Irael viene ufficialmente considerato un Membro portante del Partito, e Ambasciatore del suo Popolo presso di noi"


http://i.imgur.com/TbRr4iS.png<- Grazie Testament E:3
Ricorda...se rivolgi il tuo sguardo ^ ^ a Guardian anche Guardian volge il suo sguardo ^ ^ a te ^ ^
http://i.imgur.com/u8UJ4Vm.gifby Flame ^ ^
http://i.imgur.com/VbggEKS.gifhttp://i.imgur.com/2tJmjFJ.gifhttp://projectste.altervista.org/Our_Hero_adotta/ado2.png
Grazie Testament XD Fan n°1 ufficiale di PQ! :D

Viva
il Rhaxen! <- Folletto te lo avevo detto (fa pure rima) che non
avevo programmi di grafica per fare un banner su questo pc XD (ora ho di
nuovo il mio PC veramente :D)

Rosso Guardiano della
http://i.imgur.com/Os5rvhx.png

Rpg2s RPG BY FORUM:

Nome: Darth Reveal

 

PV totali 2
PA totali 16

Descrizione: ragazzo dai lunghi capelli rossi ed occhi dello stesso colore. Indossa una elegante giacca rossa sopra ad una maglietta nera. Porta pantaloni rossi larghi, una cintura nera e degli stivali dello stesso colore. E' solito trasportare lo spadone dietro la schiena in un fodero apposito. Ha un pendente al collo e tiene ben legato un pezzo di stoffa (che gli sta particolarmente a cuore) intorno al braccio sinistro sotto la giacca, copre una cicatrice.
Bozze vesti non definitive qui.

Equipaggiamento:
Indossa:
60$ e 59$ divisi in due tasche interne
Levaitan

Spada a due mani elsa lunga

Guanti del Defender (2PA)
Anello del linguaggio animale (diventato del Richiamo)

Scrinieri da lanciere (2 PA)

Elmo del Leone (5 PA)

Corazza del Leone in Ferro Corrazzato (7 PA)

ZAINO (20) contenente:
Portamonete in pelle di cinghiale contenente: 100$
Scatola Sanitaria Sigillata (può contenere e tenere al sicuro fino a 4 oggetti curativi) (contiene Benda di pronto soccorso x3, Pozione di cura)
Corda
Bottiglia di idromele
Forma di formaggio
Torcia (serve ad illuminare, dura tre settori)

Fiasca di ceramica con Giglio Amaro (Dona +1PN e Velocità all'utilizzatore)
Ampolla Bianca

Semi di Balissa

 

CAVALLO NORMALE + SELLA (30 +2 armi) contentente:
66$
Benda di pronto soccorso x3
Spada a due mani

Fagotto per Adara (fazzoletto ricamato)


 

Link to comment
Share on other sites

Merito per lo più di game_guy. :)

 

Trovo che possa essere utile soprattutto se unito al Modulo di Supporto di Holy.

O per permettere caricamenti di oggetti di gioco da file di testo (come lo userò io).

Aurora Dreaming


The Dreamer (v. 1.1) - standalone


72 MB - Il prequel ad Aurora Dreaming



segui il dev-diary ufficiale di Aurora Dreaming!



Bacheca Premi


http://www.rpg2s.net/forum/uploads/monthly_01_2014/post-6-0-39588100-1390575633.png

Link to comment
Share on other sites

Oppure per creare delle mod (come forse farò io)

"Io non volevo solo partecipare alle discussioni. Volevo avere il potere di farle fallire" [cit.]

http://holyres.altervista.org/UserBoard/BannerOverdrive35.png
http://holyres.altervista.org/UserBoard/Cap3.png

http://www.indiexpo.net/signature/578.png

Miei script per RPG Maker VX Ace:


*NB Tutti i miei script sono protetti da licenza CC - BY http://i.creativecommons.org/l/by/3.0/88x31.png

Questa licenza permette a terzi di distribuire, modificare, ottimizzare ed utilizzare la tua opera come base, anche commercialmente, fino a che ti diano il credito per la creazione originale. Questa è la più accomodante delle licenze offerte. É raccomandata per la diffusione e l'uso massimo di materiali coperti da licenza.

 

 



I miei tutorial:


Come distribuire il gioco - e anche come creare un'installazione professionale!
RGSS in pillole - Guida completa e facile all'RGSS2 e RGSS3 per novizi ed esperti
Come mappare con VX (e VX Ace) - guida base all'uso degli strumenti del mapping
Loop delle musiche - come tagliarle in modo da far venire musiche continue senza interruzioni finali
Creare backup dei progetti - per evitare di uccidervi dopo un errore che ha fatto perdere tutto!

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...