Questo sito utilizza cookies solo per scopi di autenticazione sul sito e nient'altro. Nessuna informazione personale viene tracciata. Leggi l'informativa sui cookies.
Username: Password: oppure
Humor - Non userò le espressioni regolari
Forum - Humor - Non userò le espressioni regolari

Avatar
TheDarkJuster (Member)
Guru^2


Messaggi: 1620
Iscritto: 27/09/2013

Segnala al moderatore
Postato alle 17:06
Martedì, 28/07/2015
Non userò le espressioni regolari, Non userò le espressioni regolari, Non userò le espressioni regolari, Non userò le espressioni regolari, Non userò le espressioni regolari, Non userò le espressioni regolari

Codice sorgente - presumibilmente Delphi

  1. function JSONEncodedToArray($JSONEncoded) {
  2.         //do nothing if not serializable
  3.         if (strlen($JSONEncoded) < 7)
  4.         {
  5.             throw new JSONException("It is not possible to decode a JSON content that doesn't contains at least 7 characters", -2);
  6.         }
  7.            
  8.         //the shortening process result
  9.         $shortenedJSON = $JSONEncoded;
  10.        
  11.         //short the JSON string to obtain maximum speed at the decode stage
  12.         $replaceTimes = 1;
  13.         while ($replaceTimes != 0)
  14.         {    $shortenedJSON = str_replace("  ", " ", $shortenedJSON, $replaceTimes);      }
  15.         $replaceTimes = 1;
  16.         while ($replaceTimes != 0)
  17.         {    $shortenedJSON = str_replace("\n", "", $shortenedJSON, $replaceTimes);      }
  18.         $replaceTimes = 1;
  19.         while ($replaceTimes != 0)
  20.         {    $shortenedJSON = str_replace("\t", "", $shortenedJSON, $replaceTimes);      }
  21.        
  22.         $JSONIsCleanAndReady = FALSE;
  23.        
  24.         while (!$JSONIsCleanAndReady) {
  25.             $JSONIsCleanAndReady = TRUE;
  26.            
  27.             //delete the starting space
  28.             if ($shortenedJSON[0] == ' ') {
  29.                 $shortenedJSON = substr($shortenedJSON, 1);
  30.                 $JSONIsCleanAndReady = FALSE;
  31.             }
  32.                
  33.  
  34.             //delete the final space
  35.             $shortenedJSONLength = strlen($shortenedJSON);
  36.             if ($shortenedJSON[$shortenedJSONLength - 1] == ' ') {
  37.                 $shortenedJSON = substr($shortenedJSON, 0, $shortenedJSONLength - 1);
  38.                 $JSONIsCleanAndReady = FALSE;
  39.             }
  40.                
  41.             //delete the beginning {
  42.             if ($shortenedJSON[0] == '{') {
  43.                 $shortenedJSON = substr($shortenedJSON, 1);
  44.                 $JSONIsCleanAndReady = FALSE;
  45.             }
  46.                
  47.             //delete the final }
  48.             $shortenedJSONLength = strlen($shortenedJSON);
  49.             if ($shortenedJSON[$shortenedJSONLength - 1] == '}') {
  50.                 $shortenedJSON = substr($shortenedJSON, 0, $shortenedJSONLength - 1);
  51.                 $JSONIsCleanAndReady = FALSE;
  52.             }
  53.         }
  54.        
  55.         //split the shortened string into characters
  56.         $JSONChars = str_split($shortenedJSON);
  57.         $JSONCharsNumber = count($JSONChars);
  58.        
  59.         $endOfJSONObject = FALSE;
  60.        
  61.         //setup an empty array
  62.         $resultingArray = array();
  63.        
  64.         //what is the cycle currently parsing?
  65.         /* $parsing Value   |   meaning
  66.          *      0           |   nothing
  67.          *      1           |   name
  68.          *      2           |   value
  69.          *      3           |   aftername
  70.          */
  71.         $parsing = 0;
  72.        
  73.         //the last parsed property name
  74.         $lastPropertyNameParsed = "";
  75.        
  76.         //the last parsed property value
  77.         $lastPropertyValueParsed = "";
  78.        
  79.         //the last parsed property type
  80.         /* $lastPropertyValueParsedType Value   |   meaning
  81.          *              0                       |   null
  82.          *              1                       |   string
  83.          *              2                       |   number
  84.          *              3                       |   object
  85.          *              4                       |   boolean
  86.          */
  87.         $lastPropertyValueParsedType = -1;
  88.        
  89.         //used to read JSON objects inside other objects
  90.         $parenthesis = 0;
  91.         $lastSaved = FALSE;
  92.        
  93.         //cycle each character starting from the first one
  94.         reset($JSONChars);
  95.         for ($i = 0; $i < $JSONCharsNumber; $i++)
  96.         {
  97.             //get the current character
  98.             $currentCharacter = current($JSONChars);
  99.            
  100.             if ((($currentCharacter == ' ') && ($lastPropertyValueParsedType == 1) && ($parsing == 2)) || (($currentCharacter == ' ') && ($lastPropertyValueParsedType == 3) && ($parsing == 2)) || ($currentCharacter != ' ') || (($currentCharacter == ' ') && ($parsing == 1)) || (($currentCharacter == ',') && ($parsing != 0)))
  101.             {
  102.                 if ($parsing == 0)
  103.                 {
  104.                     if ($currentCharacter != '"')
  105.                     {    
  106.                         throw new JSONException("Unexpected character '".$currentCharacter."', expected character '\"' instead", -6);
  107.                     } else {
  108.                         $parsing = 1;
  109.                         $lastPropertyNameParsed = "";
  110.                     }
  111.                 } else if ($parsing == 1) {
  112.                     if ($currentCharacter != '"')
  113.                     {
  114.                         $lastPropertyNameParsed = $lastPropertyNameParsed.$currentCharacter;
  115.                     } else {
  116.                         $parsing = 3;
  117.                         $lastSaved = FALSE;
  118.                     }
  119.                 }  else if ($parsing == 3) {
  120.                     if ($currentCharacter != ':')
  121.                     {   throw new JSONException("The JSON is not valid: unexpected character '".$currentCharacter."', after a json property name the ':' character is expected", -7);     }
  122.                     else
  123.                     {   $parsing = 2; $lastPropertyValueParsed = "";      }
  124.                 } else if ($parsing == 2) {
  125.                     //get the json property value type
  126.                     if ((strlen($lastPropertyValueParsed) == 0) && ($lastPropertyValueParsedType == -1)) {
  127.                         if ($currentCharacter == "\"") {
  128.                             $lastPropertyValueParsedType = 1;
  129.                             $lastPropertyValueParsed = "";
  130.                         } else if ($currentCharacter == 'n') {
  131.                             $lastPropertyValueParsed = "n";
  132.                             $lastPropertyValueParsedType = 0;
  133.                         } else if (($currentCharacter == 't') || ($currentCharacter == 'f')) {
  134.                             $lastPropertyValueParsed = "".$currentCharacter;
  135.                             $lastPropertyValueParsedType = 4;
  136.                         } else if (($currentCharacter == '0') || ($currentCharacter == '1') || ($currentCharacter == '2') || ($currentCharacter == '3') || ($currentCharacter == '4') || ($currentCharacter == '5') || ($currentCharacter == '6') || ($currentCharacter == '7') || ($currentCharacter == '8') || ($currentCharacter == '9')) {
  137.                             $lastPropertyValueParsed = "".$currentCharacter;
  138.                             $lastPropertyValueParsedType = 2;
  139.                         } else if ($currentCharacter == '{') {
  140.                             $lastPropertyValueParsed = "";
  141.                             $lastPropertyValueParsedType = 3;
  142.                             $parenthesis = 1;
  143.                         } else {
  144.                             throw new JSONException("Unrecognized JSON property type.", -8);
  145.                         }
  146.                     } else {
  147.                         if  ((($lastPropertyValueParsedType != 1) && ($lastPropertyValueParsedType != 3)) && ($currentCharacter == ',')) {
  148.                             //end of number, boolean or null parsing
  149.                             $parsing = 0;
  150.                         } else if (($lastPropertyValueParsedType == 1) && ($currentCharacter == '"')) {
  151.                             //end of string parsing
  152.                             $parsing = 0;
  153.                            
  154.                             while ((current($JSONChars) != ",") && ($i < $JSONCharsNumber)) {
  155.                                 next($JSONChars);
  156.                                 $i++;
  157.                             }
  158.                         } else {
  159.                             if ($lastPropertyValueParsedType == 3)
  160.                             {
  161.                                 //watch out for parenthesis
  162.                                 if ($currentCharacter == '{')
  163.                                     $parenthesis++;
  164.                                 else if ($currentCharacter == '}')
  165.                                    $parenthesis--;
  166.  
  167.                                if ($parenthesis == 0)
  168.                                {
  169.                                    $endOfJSONObject = TRUE;
  170.  
  171.                                    //end of object parsing
  172.                                    $parsing = 0;
  173.                                }
  174.                            }
  175.                            
  176.                            //store the last character
  177.                            if (!$endOfJSONObject)
  178.                                $lastPropertyValueParsed = $lastPropertyValueParsed.$currentCharacter;
  179.  
  180.                            $endOfJSONObject = FALSE;
  181.                        }
  182.  
  183.                        if ($parsing == 0) {
  184.                            $lastSaved = TRUE;
  185.                            
  186.                            if ($lastPropertyValueParsedType == 1)
  187.                            {
  188.                                $resultingArray[$lastPropertyNameParsed] = $lastPropertyValueParsed;
  189.                            }
  190.                            else if ($lastPropertyValueParsedType == 0)
  191.                            {  
  192.                                if ($lastPropertyValueParsed == "null")
  193.                                    $resultingArray[$lastPropertyNameParsed] = NULL;
  194.                                else
  195.                                    throw new JSONException("Unrecognized JSON value, expected \"null\", found \"".$lastPropertyValueParsed."\"", -9);
  196.                            }
  197.                            else if ($lastPropertyValueParsedType == 2)
  198.                            {
  199.                                if (is_numeric($lastPropertyValueParsedType)) {
  200.                                    if (strpos($lastPropertyValueParsed, '.') == FALSE)
  201.                                        $resultingArray[$lastPropertyNameParsed] = intval($lastPropertyValueParsed);
  202.                                    else
  203.                                        $resultingArray[$lastPropertyNameParsed] = floatval($lastPropertyValueParsed);
  204.                                } else {
  205.                                    throw new JSONException("Invalid representation of a number", -10);
  206.                                }
  207.                            }
  208.                            else if ($lastPropertyValueParsedType == 3)
  209.                            {
  210.                                $resultingArray[$lastPropertyNameParsed] = $this->JSONEncodedToArray($lastPropertyValueParsed);
  211.                            }
  212.                            else if ($lastPropertyValueParsedType == 4)
  213.                            {
  214.                                if ($lastPropertyValueParsed == "true") {
  215.                                    $resultingArray[$lastPropertyNameParsed] = TRUE;
  216.                                } else if ($lastPropertyValueParsed == "false") {
  217.                                    $resultingArray[$lastPropertyNameParsed] = FALSE;
  218.                                } else {
  219.                                    throw new JSONException("Unexpected JSON value: true or false expected, ".$lastPropertyValueParsed." found", -9);
  220.                                }
  221.                            }
  222.                            
  223.                            $lastPropertyValueParsedType = -1;
  224.                        }
  225.                    }
  226.                }
  227.            }
  228.            
  229.            //jump to the next character
  230.            next($JSONChars);
  231.        }
  232.        
  233.        if (!$lastSaved) {  
  234.            if ($lastPropertyValueParsedType == 1)
  235.            {
  236.                $resultingArray[$lastPropertyNameParsed] = $lastPropertyValueParsed;
  237.            }
  238.            else if ($lastPropertyValueParsedType == 0)
  239.            {  
  240.                if ($lastPropertyValueParsed == "null")
  241.                    $resultingArray[$lastPropertyNameParsed] = NULL;
  242.                else
  243.                    throw new JSONException("Unrecognized JSON value, expected \"null\", found \"".$lastPropertyValueParsed."\"", -9);
  244.            }
  245.            else if ($lastPropertyValueParsedType == 2)
  246.            {
  247.                if (is_numeric($lastPropertyValueParsedType)) {
  248.                    if (strpos($lastPropertyValueParsed, '.') == FALSE)
  249.                        $resultingArray[$lastPropertyNameParsed] = intval($lastPropertyValueParsed);
  250.                    else
  251.                        $resultingArray[$lastPropertyNameParsed] = floatval($lastPropertyValueParsed);
  252.                } else {
  253.                    throw new JSONException("Invalid representation of a number", -10);
  254.                }
  255.            }
  256.            else if ($lastPropertyValueParsedType == 3)
  257.            {
  258.                $resultingArray[$lastPropertyNameParsed] = $this->JSONEncodedToArray($lastPropertyValueParsed);
  259.            }
  260.            else if ($lastPropertyValueParsedType == 4)
  261.            {
  262.                if ($lastPropertyValueParsed == "true") {
  263.                    $resultingArray[$lastPropertyNameParsed] = TRUE;
  264.                } else if ($lastPropertyValueParsed == "false") {
  265.                    $resultingArray[$lastPropertyNameParsed] = FALSE;
  266.                } else {
  267.                    throw new JSONException("Unexpected JSON value: true or false expected, ".$lastPropertyValueParsed." found", -9);
  268.                }
  269.            }    
  270.            $lastPropertyValueParsedType = -1;
  271.        }
  272.        
  273.        //return the given array
  274.        return $resultingArray;
  275.    }



Qualcuno voleva un po' di spaghetti code? :asd::asd::asd:
Scusate ma non posso trattenermi dal postarlo :asd: Questa cosa di non voler mai usare le espressioni regolari mi sta sfuggendo di mano :rotfl::rotfl::rotfl:
Qualcun altro si rifiuta categoricamente di usare le regex?

PM Quote
Avatar
pierotofy (Admin)
Guru^2


Messaggi: 6230
Iscritto: 04/12/2003

Segnala al moderatore
Postato alle 23:55
Martedì, 28/07/2015
json_decode non ti piaceva?

http://php.net/manual/en/function.json-decode.php

Le regex hanno molti vantaggi; a meno che non ci sia un particolare bisogno di performance. Ma anche lì, spesso basta prestare un pò di attenzione mentre si scrivono.

Ultima modifica effettuata da pierotofy il 28/07/2015 alle 23:56


Il mio blog: https://piero.dev
PM Quote
Avatar
TheDarkJuster (Member)
Guru^2


Messaggi: 1620
Iscritto: 27/09/2013

Segnala al moderatore
Postato alle 0:17
Mercoledì, 29/07/2015
No il json_decode non mi piace, infatti se faccio il json_decode di un array php esce un array json, io voglio che da un array php esca un oggetto json, non un array json. Infatti gli array json non sono gestiti dalla mia classe, perchè non mi servono.

PM Quote
Avatar
netarrow (Admin)
Guru^2


Messaggi: 2502
Iscritto: 12/05/2004

Segnala al moderatore
Postato alle 22:38
Sabato, 01/08/2015
Riguardo le regex c'è un epico post molto Humor su stackoverflow, riguarda nel caso specifico l'uso di regex per parsare HTML:

http://stackoverflow.com/questions/1732348/regex-match-ope ...

PM Quote
Avatar
pierotofy (Admin)
Guru^2


Messaggi: 6230
Iscritto: 04/12/2003

Segnala al moderatore
Postato alle 2:09
Domenica, 02/08/2015
lol, fantastico.


Il mio blog: https://piero.dev
PM Quote