Beispiel #1
0
  private void encode_obj(PyList rval, PyObject obj, int indent_level) {
    /* Encode Python object obj to a JSON term, rval is a PyList */
    if (obj == Py.None) {
      rval.append(new PyString("null"));
    } else if (obj == Py.True) {
      rval.append(new PyString("true"));
    } else if (obj == Py.False) {
      rval.append(new PyString("false"));
    } else if (obj instanceof PyString) {
      rval.append(encode_string(obj));
    } else if (obj instanceof PyInteger || obj instanceof PyLong) {
      rval.append(obj.__str__());
    } else if (obj instanceof PyFloat) {
      rval.append(encode_float(obj));
    } else if (obj instanceof PyList || obj instanceof PyTuple) {
      encode_list(rval, obj, indent_level);
    } else if (obj instanceof PyDictionary) {
      encode_dict(rval, (PyDictionary) obj, indent_level);
    } else {
      PyObject ident = checkCircularReference(obj);
      if (defaultfn == Py.None) {
        throw Py.TypeError(String.format(".80s is not JSON serializable", obj.__repr__()));
      }

      PyObject newobj = defaultfn.__call__(obj);
      encode_obj(rval, newobj, indent_level);
      if (ident != null) {
        markers.__delitem__(ident);
      }
    }
  }
Beispiel #2
0
  private void encode_dict(PyList rval, PyDictionary dct, int indent_level) {
    /* Encode Python dict dct a JSON term */
    if (dct.__len__() == 0) {
      rval.append(new PyString("{}"));
      return;
    }

    PyObject ident = checkCircularReference(dct);
    rval.append(new PyString("{"));

    /* TODO: C speedup not implemented for sort_keys */

    int idx = 0;
    for (PyObject key : dct.asIterable()) {
      PyString kstr;

      if (key instanceof PyString || key instanceof PyUnicode) {
        kstr = (PyString) key;
      } else if (key instanceof PyFloat) {
        kstr = encode_float(key);
      } else if (key instanceof PyInteger || key instanceof PyLong) {
        kstr = key.__str__();
      } else if (key == Py.True) {
        kstr = new PyString("true");
      } else if (key == Py.False) {
        kstr = new PyString("false");
      } else if (key == Py.None) {
        kstr = new PyString("null");
      } else if (skipkeys) {
        continue;
      } else {
        throw Py.TypeError(String.format("keys must be a string: %.80s", key.__repr__()));
      }

      if (idx > 0) {
        rval.append(item_separator);
      }

      PyObject value = dct.__getitem__(key);
      PyString encoded = encode_string(kstr);
      rval.append(encoded);
      rval.append(key_separator);
      encode_obj(rval, value, indent_level);
      idx += 1;
    }

    if (ident != null) {
      markers.__delitem__(ident);
    }
    rval.append(new PyString("}"));
  }