A middleware that parses the body of json requests and
    add it to the request under the `body` attribute (replacing
    the previous value). Can preserve the original value in
    a new attribute `raw_body` if you give preserve_raw_body=True.
974080
def wrap_json_body(func=None, *, preserve_raw_body=False):
    

    if func is None:
        return functools.partial(
            wrap_json_body,
            preserve_raw_body=preserve_raw_body
        )

    @functools.wraps(func)
    def wrapper(request, *args, **kwargs):
        ctype, pdict = parse_header(request.headers.get('Content-Type', ''))
        if preserve_raw_body:
            request.raw_body = request.body
        if ctype == "application/json":
            request.body = json.loads(request.body.decode("utf-8")) if request.body else None
        return func(request, *args, **kwargs)
    return wrapper
1301675
def wrap_json_params(func):
    

    @functools.wraps(func)
    def wrapper(request, *args, **kwargs):
        ctype, pdict = parse_header(request.headers.get('Content-Type', ''))
        if ctype == "application/json":
            request.params = json.loads(request.body.decode("utf-8")) if request.body else None
        return func(request, *args, **kwargs)
    return wrapper
430058
def parse_request(request, input_schema, raw):
    """"""

    request.json = {}
    if not raw:
        body = yield from request.read()
        if body:
            try:
                request.json = json.loads(body.decode('utf-8'))
            except ValueError as e:
                request.json = {"malformed_json": body.decode('utf-8')}
                raise aiohttp.web.HTTPBadRequest(text="Invalid JSON {}".format(e))

    # Parse the query string
    if len(request.query_string) > 0:
        for (k, v) in urllib.parse.parse_qs(request.query_string).items():
            request.json[k] = v[0]

    if input_schema:
        try:
            jsonschema.validate(request.json, input_schema)
        except jsonschema.ValidationError as e:
            log.error("Invalid input query. JSON schema error: {}".format(e.message))
            raise aiohttp.web.HTTPBadRequest(text="Invalid JSON: {} in schema: {}".format(
                e.message,
                json.dumps(e.schema)))

    return request
520831
function jsonBodyParser(options) {
    assert.optionalObject(options, 'options');
    var opts = options || {};

    var override = opts.overrideParams;

    function parseJson(req, res, next) {
        // save original body on req.rawBody and req._body
        req.rawBody = req._body = req.body;

        if (req.getContentType() !== 'application/json' || !req.body) {
            return next();
        }

        var params;

        try {
            params = JSON.parse(req.body, opts.reviver);
        } catch (e) {
            return next(new errors.InvalidContentError('Invalid JSON: ' +
                e.message));
        }

        if (opts.mapParams === true) {
            if (Array.isArray(params)) {
                // if req.params exists, we have url params. we can't map an
                // array safely onto req.params, throw an error.
                if (req.params &&
                    Object.keys(req.params).length > 0 &&
                    !(req.params instanceof Array)) {
                    return next(new errors.InternalServerError(
                        'Cannot map POST body of [Array array] onto req.params'
                    ));
                }
                req.params = params;
            } else if (typeof (params) === 'object' && params !== null) {
                // else, try to merge the objects
                Object.keys(params).forEach(function (k) {
                    var p = req.params[k];

                    if (p && !override) {
                        return;
                    }
                    req.params[k] = params[k];
                });
            } else {
                // otherwise, do a wholesale stomp, no need to merge one by one.
                req.params = params || req.params;
            }
        }

        req.body = params;

        return next();
    }

    var chain = [];

    if (!opts.bodyReader) {
        chain.push(bodyReader(opts));
    }
    chain.push(parseJson);
    return chain;
}
1201838
def parse_json(body)
      buf = {}

      begin
        buf = JSON.parse(body)
      rescue JSON::ParserError
      end

      buf
    end
594491
def send_http_request_with_json(context, method):
    
    safe_add_http_request_context_to_behave_context(context)
    context.http_request_context.body_params = json.loads(context.text)
    context.http_request_context.renderer = JSONRenderer()
    send_http_request(context, method)
890352
function json (options) {
  var opts = options || {}

  var limit = typeof opts.limit !== 'number'
    ? bytes.parse(opts.limit || '100kb')
    : opts.limit
  var inflate = opts.inflate !== false
  var reviver = opts.reviver
  var strict = opts.strict !== false
  var type = opts.type || 'application/json'
  var verify = opts.verify || false

  if (verify !== false && typeof verify !== 'function') {
    throw new TypeError('option verify must be function')
  }

  // create the appropriate type checking function
  var shouldParse = typeof type !== 'function'
    ? typeChecker(type)
    : type

  function parse (body) {
    if (body.length === 0) {
      // special-case empty json body, as it's a common client-side mistake
      // TODO: maybe make this configurable or part of "strict" option
      return {}
    }

    if (strict) {
      var first = firstchar(body)

      if (first !== '{' && first !== '[') {
        debug('strict violation')
        throw new SyntaxError('Unexpected token ' + first)
      }
    }

    debug('parse json')
    return JSON.parse(body, reviver)
  }

  return function jsonParser (req, res, next) {
    if (req._body) {
      debug('body already parsed')
      next()
      return
    }

    req.body = req.body || {}

    // skip requests without bodies
    if (!typeis.hasBody(req)) {
      debug('skip empty body')
      next()
      return
    }

    debug('content-type %j', req.headers['content-type'])

    // determine if request should be parsed
    if (!shouldParse(req)) {
      debug('skip parsing')
      next()
      return
    }

    // assert charset per RFC 7159 sec 8.1
    var charset = getCharset(req) || 'utf-8'
    if (charset.substr(0, 4) !== 'utf-') {
      debug('invalid charset')
      next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', {
        charset: charset
      }))
      return
    }

    // read
    read(req, res, next, parse, debug, {
      encoding: charset,
      inflate: inflate,
      limit: limit,
      verify: verify
    })
  }
}
281083
def _put(self, *args, **kwargs):
        
        if 'data' in kwargs:
            kwargs['data'] = json.dumps(kwargs['data'])
        response = requests.put(*args, **kwargs)
        response.raise_for_status()
1171987
def request_body items
      { type: type, action: action, domain: domain, objects: items }.to_json
    end
606282
def __stringify_body(self, request_or_response):
        '''  '''
        headers = self.__track_info['{}_headers'.format(request_or_response)]
        body = self.__track_info.get('{}_body'.format(request_or_response))
    
        if isinstance(body, CaseInsensitiveDict):
            body = json.dumps(dict(body), ensure_ascii=False)
    
        elif isinstance(body, (dict, list)):
            body = json.dumps(body, indent=2, ensure_ascii=False)
    
        elif isinstance(body, bytes):
            resp_content_type = headers.get("Content-Type", "")
            try:
                if "image" in resp_content_type:
                    self.__track_info["response_data_type"] = "image"
                    body = "data:{};base64,{}".format(
                        resp_content_type,
                        b64encode(body).decode('utf-8')
                    )
                else:
                    body = escape(body.decode("utf-8"))
            except UnicodeDecodeError:
                pass
    
        elif not isinstance(body, (basestring, numeric_types, Iterable)):
            # class instance, e.g. MultipartEncoder()
            body = repr(body)
    
        self.__track_info['{}_body'.format(request_or_response)] = body
1041410
def create_new(self, body):
        
        return self.client.post(self._url(), data=body)
1133753
def flatten_json_request_body(prefix, dict_body, spec):
    """"""
    if len(spec) == 1 and 'type' in spec:
        return {prefix: to_str(dict_body, spec)}

    flat = {}
    for key, value in dict_body.items():
        node_type = spec[key]['type']
        if node_type == 'list':
            for idx, v in enumerate(value, 1):
                pref = key + '.member.' + str(idx)
                flat.update(flatten_json_request_body(
                    pref, v, spec[key]['member']))
        elif node_type == 'map':
            for idx, (k, v) in enumerate(value.items(), 1):
                pref = key + '.entry.' + str(idx)
                flat.update(flatten_json_request_body(
                    pref + '.key', k, spec[key]['key']))
                flat.update(flatten_json_request_body(
                    pref + '.value', v, spec[key]['value']))
        else:
            flat.update(flatten_json_request_body(key, value, spec[key]))

    if prefix:
        prefix = prefix + '.'
    return dict((prefix + k, v) for k, v in flat.items())
357328
def treat(request_body):
    
    # Python 3+ support
    if isinstance(request_body, six.binary_type):
        request_body = request_body.decode('utf-8')

    try:
        data = json.loads(request_body)
    except ValueError:
        raise exceptions.UnknownAPIResource('Request body is malformed JSON.')

    unsafe_api_resource = APIResource.factory(data)

    try:
        consistent_api_resource = unsafe_api_resource.get_consistent_resource()
    except AttributeError:
        raise exceptions.UnknownAPIResource('The API resource provided is invalid.')

    return consistent_api_resource
630509
def request(method, path, params=None, data=None, auto_retry=True):
    
    body = None
    if data is not None:
        body = json.dumps(data, cls=utils.DateTimeEncoder)

    headers = {
        'accept': 'application/json',
        'content-type': 'application/json',
        'user-agent': analyzere.user_agent,
    }
    resp = request_raw(method, path, params=params, body=body, headers=headers,
                       auto_retry=auto_retry)
    content = resp.text
    if content:
        try:
            content = json.loads(content, cls=utils.DateTimeDecoder)
        except ValueError:
            raise errors.ServerError('Unable to parse JSON response returned '
                                     'from server.', resp, resp.status_code)
    return content
983350
def with_json(self, data=None, **params):
        
        if isinstance(data, (tuple, list)):
            data = dict(data)

        if params:
            # data must be None or able to be a dict
            if isinstance(data, dict):
                data.update(params)
            elif data is None:
                data = params
            else:
                raise ValueError('Data must be None or a dict if used with params, got: %r' % data)

        req = self.with_headers({'Content-Type': 'application/json', 'Accept': 'application/json'})
        if isinstance(data, basestring):
            # Looks like it's already been encoded
            return req.with_body(data)
        else:
            return req.with_body(json.dumps(data))
1000333
def put(self, endpoint, **kwargs):
        
        kwargs.update(self.kwargs.copy())
        if "data" in kwargs:
            kwargs["headers"].update(
                {"Content-Type": "application/json;charset=UTF-8"})
        response = requests.put(self.make_url(endpoint), **kwargs)
        return _decode_response(response)
888842
def _put(self, uri, data):
        
        headers = self._get_headers()

        logging.debug("URI=" + str(uri))
        logging.debug("BODY=" + json.dumps(data))

        response = self.session.put(uri, headers=headers,
                data=json.dumps(data))
        if response.status_code in [201, 204]:
            return data
        else:
            logging.error(response.content)
            response.raise_for_status()