Convert an ElementTree or Element into a JSON string.
334616
def elem2json(elem, options, strip_ns=1, strip=1):

    """"""

    if hasattr(elem, 'getroot'):
        elem = elem.getroot()

    if options.pretty:
        return json.dumps(elem_to_internal(elem, strip_ns=strip_ns, strip=strip), sort_keys=True, indent=4, separators=(',', ': '))
    else:
        return json.dumps(elem_to_internal(elem, strip_ns=strip_ns, strip=strip))
660666
def serialise(self, element: Element, **kwargs) -> str:
        

        return json.dumps(self.serialise_dict(element), **kwargs)
448169
def _to_dict(xmltree):
    '''
    
    '''
    # If this object has no children, the for..loop below will return nothing
    # for it, so just return a single dict representing it.
    if not xmltree.getchildren():
        name = _conv_name(xmltree.tag)
        return {name: xmltree.text}

    xmldict = {}
    for item in xmltree:
        name = _conv_name(item.tag)

        if name not in xmldict:
            if item.getchildren():
                xmldict[name] = _to_dict(item)
            else:
                xmldict[name] = item.text
        else:
            # If a tag appears more than once in the same place, convert it to
            # a list. This may require that the caller watch for such a thing
            # to happen, and behave accordingly.
            if not isinstance(xmldict[name], list):
                xmldict[name] = [xmldict[name]]
            xmldict[name].append(_to_dict(item))
    return xmldict
746423
private static String toJsonStr(Object object) throws JsonGenerationException, JsonMappingException, IOException{
        return mapper.writeValueAsString(object);
    }
292476
protected JSONObject elementToJson(CmsContainerElementBean element, Set<String> excludeSettings) {

        JSONObject data = null;
        try {
            data = new JSONObject();
            data.put(FavListProp.ELEMENT.name().toLowerCase(), element.getId().toString());
            if (element.getFormatterId() != null) {
                data.put(FavListProp.FORMATTER.name().toLowerCase(), element.getFormatterId().toString());
            }
            JSONObject properties = new JSONObject();
            for (Map.Entry<String, String> entry : element.getIndividualSettings().entrySet()) {
                String settingKey = entry.getKey();
                if (!excludeSettings.contains(settingKey)) {
                    properties.put(entry.getKey(), entry.getValue());
                }
            }
            data.put(FavListProp.PROPERTIES.name().toLowerCase(), properties);
        } catch (JSONException e) {
            // should never happen
            if (!LOG.isDebugEnabled()) {
                LOG.warn(e.getLocalizedMessage());
            }
            LOG.debug(e.getLocalizedMessage(), e);
            return null;
        }
        return data;
    }
568258
function xml2json( xml ) {
  try {
    var obj = {};
    if ( xml.children.length > 0 ) {
      for ( var i = 0; i < xml.children.length; i++ ) {
        var item = xml.children.item( i )
        var nodeName = item.nodeName

        if ( typeof (obj[nodeName]) == "undefined" ) {
          obj[nodeName] = xml2json( item )
        } else {
          if ( typeof (obj[nodeName].push) == "undefined" ) {
            var old = obj[nodeName]

            obj[nodeName] = []
            obj[nodeName].push( old )
          }
          obj[nodeName].push( xml2json( item ) )
        }
      }
    } else {
      obj = xml.textContent
    }
    return obj
  } catch ( e ) {
    log( "PongRss", e.message )
  }
}
72378
def tree_to_html(tree):
    """"""
    ul = etree.Element('ul')
    html_listify([tree], ul)
    return HTML_WRAPPER.format(etree.tostring(ul))
1230087
def tostring(self, root=None, doctype=None, pretty_print=True):
        """"""
        if root is None:
            root = self.root
        return etree.tounicode(
            root, doctype=doctype or self.info.doctype, pretty_print=pretty_print
        )
764316
def xml_to_str(tree, encoding=None, xml_declaration=False):
    """"""
    if xml_declaration and not encoding:
        raise ValueError("'xml_declaration' is not supported when 'encoding' is None")
    if encoding:
        return tostring(tree, encoding=encoding, xml_declaration=True)
    return tostring(tree, encoding=text_type, xml_declaration=False)
1222618
def jsonise(dic):
        """"""
        d = {}
        for k, v in dic.items():
            if type(v) in abstractRequetesSQL.TYPES_PERMIS:
                d[k] = v
            else:
                try:
                    d[k] = json.dumps(v, ensure_ascii=False, cls=formats.JsonEncoder)
                except ValueError as e:
                    logging.exception("Erreur d'encodage JSON !")
                    raise e
        return d
1293513
def _jsonify(x):
    """"""
    if isinstance(x, dict_class):
        return json.dumps(x._d, separators=(',', ':'))
    return json.dumps(x, separators=(',', ':'))
404783
function xmlToJson(withStar, xml) {
  var XML_STAR_VAR = "__STAR_VAR__", XML_EQUAL_TO = '{{*}}';
  
  var getTextContent = function(str){
    return str.trim();
  };

  var isValidXMLStar = function(withStar, vl){
    return withStar && vl && (vl.trim() === XML_STAR_VAR);
  };

  var replaceXMLStar = function(withStar, str){
    if(isValidXMLStar(withStar, str)){
      return XML_EQUAL_TO;
    } else {
      return str;
    }
  };

  // Create the return object
  var obj = {};

  if (xml.nodeType == 1) { // element
    // do attributes
    obj["@attributes"] = {};
    if (xml.attributes.length > 0) {
      for (var j = 0; j < xml.attributes.length; j++) {
        var attribute = xml.attributes.item(j);
        var attrName = replaceXMLStar(withStar, attribute.nodeName);
        obj["@attributes"][attrName] = replaceXMLStar(withStar, attribute.nodeValue);
      }
    }
  } else if (xml.nodeType == 3) { // text
    obj = getTextContent(xml.nodeValue);
  } else if (xml.nodeType == 4) { // text
    return xml.textContent;
  }

  // do children
  if (xml.hasChildNodes && xml.hasChildNodes()) {
    for(var i = 0; i < xml.childNodes.length; i++) {
      var item = xml.childNodes.item(i);
      var nodeName = item.nodeName;
      if(isValidXMLStar(withStar, nodeName)){
        obj[XML_EQUAL_TO] = XML_EQUAL_TO;
      } else {
        if (typeof(obj[nodeName]) == "undefined") {
          obj[nodeName] = xmlToJson(withStar, item);
        } else if(nodeName !== '#text'){
          if (typeof(obj[nodeName].push) == "undefined") {
            var old = obj[nodeName];
            obj[nodeName] = [];
            obj[nodeName].push(old);
          }
          obj[nodeName].push(xmlToJson(withStar, item));
        }  
      }
    }
  }
  if(obj['#text'] && typeof obj['#text'] === 'string' && isValidXMLStar(withStar, obj['#text'])){
    obj['#text'] = XML_EQUAL_TO;
  }
  return obj;
}
812721
private String convertToString(JsonNode jsonArrayNode) {

		StringBuilder strBuilder = new StringBuilder();
		Iterator<JsonNode> nodeIterator = jsonArrayNode.iterator();
		while (nodeIterator.hasNext()) {
			JsonNode jsonNode = (JsonNode) nodeIterator.next();
			strBuilder.append(jsonNode.asText());
			if (nodeIterator.hasNext()) {
				strBuilder.append(ARRAY_VALUE_SEPARATOR);
			}
		}
		return strBuilder.toString();
	}
543260
private static String toJSON(Object data) {
        try {
            return mapper.writeValueAsString(data);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
1358341
function toJSON(node) {
  node = node || this;

  var obj = {
    nodeType: node.nodeType
  };

  if (node.tagName) {
    obj.name = node.tagName.toLowerCase();
  } else if (node.nodeName) {
    obj.name = node.nodeName.toLowerCase();
  }
  if (node.nodeValue) {
    obj.nodeValue = node.nodeValue;
  }
  var attrs = node.attributes;

  if (attrs) {
    var length = attrs.length;

    obj.props = {};
    for (var i = 0; i < length; i++) {
      var attr = attrs[i];

      obj.props[attr.nodeName] = attr.nodeValue;
    }
  }
  var childNodes = node.childNodes;

  if (childNodes) {
    var _length = childNodes.length;

    obj.children = [];
    for (var _i = 0; _i < _length; _i++) {
      obj.children.push(toJSON(childNodes[_i]));
    }
  }
  return obj;
}
1165349
def serialize_symbol(ctx, document, el, root):
    ""

    span = etree.SubElement(root, 'span')
    span.text = el.value()

    fire_hooks(ctx, document, el, span, ctx.get_hook('symbol'))

    return root
758509
def to_json(obj):
    """"""
    i = StringIO.StringIO()
    w = Writer(i, encoding='UTF-8')
    w.write_value(obj)
    return i.getvalue()