Convert rendered XML response to JSON for use with boto3.
494707
def xml_to_json_response(service_spec, operation, xml, result_node=None):
    """"""

    def transform(value, spec):
        """Apply transformations to make the output JSON comply with the
        expected form. This function applies:

          (1) Type cast to nodes with "type" property (e.g., 'true' to
              True). XML field values are all in text so this step is
              necessary to convert it to valid JSON objects.

          (2) Squashes "member" nodes to lists.

        """
        if len(spec) == 1:
            return from_str(value, spec)

        od = OrderedDict()
        for k, v in value.items():
            if k.startswith('@'):
                continue

            if k not in spec:
                # this can happen when with an older version of
                # botocore for which the node in XML template is not
                # defined in service spec.
                log.warning(
                    'Field %s is not defined by the botocore version in use', k)
                continue

            if spec[k]['type'] == 'list':
                if v is None:
                    od[k] = []
                elif len(spec[k]['member']) == 1:
                    if isinstance(v['member'], list):
                        od[k] = transform(v['member'], spec[k]['member'])
                    else:
                        od[k] = [transform(v['member'], spec[k]['member'])]
                elif isinstance(v['member'], list):
                    od[k] = [transform(o, spec[k]['member'])
                             for o in v['member']]
                elif isinstance(v['member'], OrderedDict):
                    od[k] = [transform(v['member'], spec[k]['member'])]
                else:
                    raise ValueError('Malformatted input')
            elif spec[k]['type'] == 'map':
                if v is None:
                    od[k] = {}
                else:
                    items = ([v['entry']] if not isinstance(v['entry'], list) else
                             v['entry'])
                    for item in items:
                        key = from_str(item['key'], spec[k]['key'])
                        val = from_str(item['value'], spec[k]['value'])
                        if k not in od:
                            od[k] = {}
                        od[k][key] = val
            else:
                if v is None:
                    od[k] = None
                else:
                    od[k] = transform(v, spec[k])
        return od

    dic = xmltodict.parse(xml)
    output_spec = service_spec.output_spec(operation)
    try:
        for k in (result_node or (operation + 'Response', operation + 'Result')):
            dic = dic[k]
    except KeyError:
        return None
    else:
        return transform(dic, output_spec)
    return None
1235092
function () {
        if (req.status !== 200) {
          console.warn(req.responseText);
          return;
        }
        // Show the raw response text on page
        xmlOutput.textContent = req.responseText;
        // convert XML to javascript objects
        var json = sdmxmllib.mapSDMXMLResponse(req.responseText);
        // Convert to json and show on page
        jsonOutput.textContent = JSON.stringify(json, null, 2);
    }
1216215
def parse_response(response):
    
    if response.headers.get('Content-Type', JSON_TYPE).startswith(JSON_TYPE):
        return ResponseObject(json.loads(response.body))
    else:
        return response.body
437914
def as_json(context):
    """"""
    info = {
        'info': cgi.escape(pprint.pformat(context.context)),
    }
    return Response(content_type='application/json', body=json.dumps(info))
989107
def to_json(el, schema=None):
    
    if type(el) is str:
        json_el = el
    elif type(el) is list:
        json_el = list(map(to_json, el))
    elif type(el) is dict:
        assert 'tagName' in el
        json_el = el.copy()
        if 'attributes' not in el:
            json_el['attributes'] = {}
        if 'children' not in el:
            json_el['children'] = []
    elif isinstance(el, VDOM):
        json_el = el.to_dict()
    else:
        json_el = el

    if schema:
        try:
            validate(instance=json_el, schema=schema, cls=Draft4Validator)
        except ValidationError as e:
            raise ValidationError(_validate_err_template.format(schema, e))

    return json_el
555424
def render_to_json(response, request=None, **kwargs):
    
    # determine the status code
    if hasattr(response, 'status_code'):
        status_code = response.status_code
    elif issubclass(type(response), Http404):
        status_code = 404
    elif issubclass(type(response), Exception):
        status_code = 500
        logger.exception(str(response), extra={'request': request})
        
        if settings.DEBUG:
            import sys
            reporter = ExceptionReporter(None, *sys.exc_info())
            text = reporter.get_traceback_text()
            response = HttpResponseServerError(text, content_type='text/plain')
        else:
            response = HttpResponseServerError("An error occured while processing an AJAX request.", content_type='text/plain')
    else:
        status_code = 200

    # creating main structure
    data = {
        'status': status_code,
        'statusText': REASON_PHRASES.get(status_code, 'UNKNOWN STATUS CODE'),
        'content': response
    }

    return JSONResponse(data, **kwargs)
475556
def dump_json(self, pretty=True):
        
        # Build template
        t = {}
        t['AWSTemplateFormatVersion'] = '2010-09-09'        
        if self.description is not None:
            t['Description'] = self.description
        self.elements.dump_to_template_obj(self, t)

        return _CustomJSONEncoder(indent=2 if pretty else None,
                                  sort_keys=False).encode(t)
391459
def json(self, conversion: _Text = 'badgerfish') -> Mapping:
        
        if not self._json:

            if conversion is 'badgerfish':
                from xmljson import badgerfish as serializer

            elif conversion is 'abdera':
                from xmljson import abdera as serializer

            elif conversion is 'cobra':
                from xmljson import cobra as serializer

            elif conversion is 'gdata':
                from xmljson import gdata as serializer

            elif conversion is 'parker':
                from xmljson import parker as serializer

            elif conversion is 'yahoo':
                from xmljson import yahoo as serializer

            self._json = json.dumps(serializer.data(etree.fromstring(self.xml)))

        return self._json
335913
def parse(self, response):
        
        self.headers = response.headers

        if 'xml' in self.headers.get('Content-Type'):
            # Got an XML response, likely an error code.
            xml = xmltodict.parse(response.text)
            self.analyze_reply_code(xml_response_dict=xml)

        lines = response.text.split('\r\n')
        if len(lines) < 3:
            lines = response.text.split('\n')

        for line in lines:
            line = line.strip()

            name, value = self.read_line(line)
            if name:
                if name in self.valid_transactions or re.match(pattern='/^X\-/', string=name):
                    self.capabilities[name] = value
                else:
                    self.details[name] = value
1145557
def _xml_to_dict(xml):
    '''
    
    '''
    dicts = {}
    for item in xml:
        key = item.tag.lower()
        idx = 1
        while key in dicts:
            key += six.text_type(idx)
            idx += 1
        if item.text is None:
            dicts[key] = _xml_to_dict(item)
        else:
            dicts[key] = item.text

    return dicts
1259471
def return_json_response(self, context, **request_kwargs):
        '''
        
        '''
        outline_dict = model_to_dict(self.object)
        logger.debug(str(outline_dict))
        logger.debug("Attepting to switch tags from queryset to name...")
        logger.debug(str(self.object.tags.names()))
        outline_dict.pop('tags')
        outline_dict['tags'] = list(self.object.tags.names())
        logger.debug(str(outline_dict))
        if self.object.series:
            outline_dict['series'] = model_to_dict(self.object.series)
            outline_dict['series']['tags'] = list(self.object.series.tags.names())
            logger.debug('Adding series... {}'.format(outline_dict['series']))
        if self.object.characterinstance_set.count():
            outline_dict['characters'] = []
            for cint in self.object.characterinstance_set.all():
                character_dict = model_to_dict(cint.character)
                character_dict['outline_key'] = cint.pk
                character_dict['tags'] = list(cint.character.tags.names())
                character_dict['role_properties'] = {
                    'main_character': cint.main_character,
                    'pov_character': cint.pov_character,
                    'protagonist': cint.protagonist,
                    'antagonist': cint.antagonist,
                    'villain': cint.villain,
                    'obstacle': cint.obstacle,
                }
                outline_dict['characters'].append(character_dict)
        if self.object.locationinstance_set.count():
            outline_dict['locations'] = []
            for lint in self.object.locationinstance_set.all():
                location_dict = model_to_dict(lint.location)
                location_dict['tags'] = list(lint.location.tags.names())
                location_dict['outline_key'] = lint.pk
                outline_dict['locations'].append(location_dict)
        if self.object.arc_set.count():
            outline_dict['arcs'] = []
            for arc in self.object.arc_set.all():
                arc_dict = model_to_dict(arc)
                arc_dict['nodes'] = ArcElementNode.dump_bulk(parent=arc.arc_root_node)
                outline_dict['arcs'].append(arc_dict)
        outline_dict['story_tree'] = StoryElementNode.dump_bulk(parent=self.object.story_tree_root)
        logger.debug("Sending response via JSON: {}".format(outline_dict))
        response = JsonResponse(outline_dict)
        response['Content-Disposition'] = 'attachment; filename="{}.json"'.format(slugify(self.object.title))
        return response
1000617
def parse_response!
      response.body = case @response_format
        when :xml then Hash.from_xml response.body
        when :json then JSON response.body
      end if response.body
    end
88601
def _xml_to_dict(self, element):
        
        return_dict = {}
        for el in element:
            return_dict[el.tag] = None
            children = el.getchildren()
            if children:
                return_dict[el.tag] = self._xml_to_dict(children)
            else:
                return_dict[el.tag] = el.text
        return return_dict
283788
function xmlToJson(xml) {
            // Create the return object
            var obj = {};
            if (xml.nodeType === 1) { // element
                // do attributes
                if (xml.attributes.length > 0) {
                    for (var j = 0; j < xml.attributes.length; j++) {
                        var attribute = xml.attributes.item(j);
                        obj[attribute.nodeName] = attribute.value;
                    }
                }
            } else if (xml.nodeType === 3) { // text
                obj = xml.nodeValue.trim(); // add trim here
            }
            // do children
            if (xml.hasChildNodes()) {
                for (var i = 0; i < xml.childNodes.length; i++) {
                    var item = xml.childNodes.item(i);
                    var nodeName = item.nodeName;
                    if (typeof(obj[nodeName]) === "undefined") { //$NON-NLS-0$
                        var tmp = xmlToJson(item);
                        if (tmp !== "") // if not empty string
                            obj[nodeName] = tmp;
                    } else {
                        if (typeof(obj[nodeName].push) === "undefined") { //$NON-NLS-0$
                            var old = obj[nodeName];
                            obj[nodeName] = [];
                            obj[nodeName].push(old);
                        }
                        tmp = xmlToJson(item);
                        if (tmp !== "") // if not empty string
                            obj[nodeName].push(tmp);
                    }
                }
            }
            return obj;
        }
378197
def render_to_json(templates, context, request):
    
    html = render_to_string(
        templates,
        context=context,
        request=request
    )
    _json = json.dumps({
        "html": html
    })
    return HttpResponse(_json)
1255261
def _handle_response(response, **kwargs) -> XMLResponse:
        
        if not response.encoding:
            response.encoding = DEFAULT_ENCODING

        return response
228884
def pretty_render(data, format='text', indent=0):
    
    if format == 'json':
        return render_json(data)
    elif format == 'html':
        return render_html(data)
    elif format == 'xml':
        return render_xml(data)
    else:
        return dict_to_plaintext(data, indent=indent)