Page 1 of 1

Anyone need a JSON function?

Posted: Wed Apr 02, 2008 12:57 pm
by pickle
Hi all,

I just wrote a function that will encode any array or scalar (non-object) value into JSON syntax. I didn't want to install PEAR & I don't have PHP 5.2+ so there were no pre-existing JSON functions available.

My question is: is anyone else in the same boat as me & would see benefit from me sharing the function? It's pretty rough as it is but it works for me & I don't want to clean it up if no one will use it.

Thanks.

Re: Anyone need a JSON function?

Posted: Wed Apr 02, 2008 5:36 pm
by Christopher
You could contribute it to the Skeleton framework. :) It has a JSON class that uses json_encode/decode() but does not have a fall back class. We are always looking for contributors...

Re: Anyone need a JSON function?

Posted: Tue Nov 25, 2008 3:09 pm
by pickle
Trying not to be a threadnarc, but here's the function I was talking about. This hasn't been verified to be 100% JSON compliant, but it works for everything I've thrown at it.

One note: It's recursive, but I've used __FUNCTION__, so if you need/want to rename it, you don't have to hunt through the function to make sure the recursion calls the right function.

Code: Select all

####
# Function: _jsonEncode
# Purpose: To encode a variable into json format
# Arguments: $encodeMe: the variable to convert into JSON format
#            $encodeAs : the name of the variable to save $var1 as.  
#                        REQUIRED if $encodeMe is not an array
# Usage: 
#   echo _jsonEncode('test','var1');// outputs: {"var1":test"}
#   echo _jsonEncode(TRUE,'var1');  // outputs: {"var1":1}
#   echo _jsonEncode(123,'var1');   // outputs: {"var1":123}
#   echo _jsonEncode(array('orange'=>1,'blue'=>2,'green'=>3));  // outputs: {"orange":1,"blue":2,"green":3}
# 
# Author: Dylan Anderson
# License: GPLv3
####
function _jsonEncode($encodeMe,$encodeAs=FALSE){
    $output = '{';
    
    if(is_array($encodeMe)){
        foreach($encodeMe as $key=>$value){
            $output .= '"'.$key.'":';
            
            if(is_array($value)){
                $function = __FUNCTION__;
                $output .= $function($value);
            }
            
            else if(is_numeric($value))
                $output .= $value;
 
            else
                $output .= '"'.str_replace('"','\"',$value).'"';
            
            $output .= ',';
        }
        $output = rtrim($output,',').'}';
    }
    else if(strlen($encodeAs)){
        if(is_numeric($encodeMe))
            $output .= '"'.$encodeAs.'":'.$encodeMe.'}';
        else if(is_bool($encodeMe)){
            $encode_value = ($encodeMe) ? 1 : 0;
            $output .= '"'.$encodeAs.'":'.$encode_value.'}';
        }
        else if(is_string($encodeMe))
            $output .= '"'.$encodeAs.'":'.str_replace('"','\"',$encodeMe).'"}';
    }
    else
        $output = FALSE;
 
    return($output);
}