Lightweight JavaScript JSON Encoding

Sometimes you dont need elaborate JSON encoding support, so the function below will do. Keep in mind that some builds of JavaScript provide toSource() which should be used when available.

JSON = {
  encode : function(input) {
    if (!input) return 'null'
    switch (input.constructor) {
      case String: return '"' + input + '"'
      case Number: return input.toString()
      case Array :
        var buf = []
        for (i in input)
          buf.push(JSON.encode(input[i]))
            return '[' + buf.join(', ') + ']'
      case Object:
        var buf = []
        for (k in input)
          buf.push(k + ' : ' + JSON.encode(input[k]))
            return '{ ' + buf.join(', ') + '} '
      default:
        return 'null'
    }
  }
}

Comments

In order to make this code work with PHP (json_decode function)
i've changed the code

buf.push(k + ' : ' + JSON.encode(input[k]))

with

buf.push('"'+k+'"' + ' : ' + JSON.encode(input[k]))

because the name of property must be double quoted too.