Potentially interprets a string as JSON for usage with mongo
178981
def _to_dict(objects):
    '''
    
    '''
    try:
        if isinstance(objects, six.string_types):
            objects = salt.utils.json.loads(objects)
    except ValueError as err:
        log.error("Could not parse objects: %s", err)
        raise err

    return objects
1353451
def is_json(string):
    
    if not is_full_string(string):
        return False
    if bool(JSON_WRAPPER_RE.search(string)):
        try:
            return isinstance(json.loads(string), dict)
        except (TypeError, ValueError, OverflowError):
            return False
    return False
1286382
def parse_string(string, options = {}, &block)
      parse_io(StringIO.new(string), options, &block)
    end
489550
function parseObj (input) {
  try {
    return require(path.resolve(input));
  } catch (e) {
    var str;
    try {
      str = fs.readFileSync(program.obj, 'utf8');
    } catch (e) {
      str = program.obj;
    }
    try {
      return JSON.parse(str);
    } catch (e) {
      return eval('(' + str + ')');
    }
  }
}
170248
function (object) {
		if (!object || object._bsontype)
			return object;

		if (_.isString(object))
			return object.replace(/\./g, "U+FF0E").replace(/\$/g, "U+FF04");

		var newObject = _.isArray(object) ? [ ] : { };

		Object.keys(object).forEach(function (key) {
			var sKey = key;
			
			if (/[.|$]/.test(key)) {
				sKey = mongojs.util.sanitise(key);
				newObject[sKey] = object[key];
			} else {
				newObject[key] = object[key];
			}
			
			// Recurse
			if (isObject(newObject[sKey]))
				newObject[sKey] = this.sanitise(newObject[sKey]);
		}.bind(this));
		
		return newObject;
	}
560386
function (str, parserOptions) {
  parserOptions = parserOptions || {};
  // Do a naive test whether this is a string or an object
  var mapFn = parserOptions.map ? str.trim().charAt(0) === '[' ? underscore.map : underscore.mapObject : identity;
  var jsonParser = JSON.parse;
  return mapFn(jsonParser(str, parserOptions.reviver, parserOptions.filename), parserOptions.map);
}
1264211
def load_json_from_string(string):
    """"""
    try:
        json_data = json.loads(string)
    except ValueError as e:
        raise ValueError('Given string is not valid JSON: {}'.format(e))
    else:
        return json_data
135512
def mongoqs_to_json(qs, fields=None):
    

    l = list(qs.as_pymongo())

    for element in l:
        element.pop('_cls')

    # use DjangoJSONEncoder for transform date data type to datetime
    json_qs = json.dumps(l, indent=2, ensure_ascii=False, cls=DjangoJSONEncoder)
    return json_qs
579202
def parse(string, is_file=False, obj=False):
        
        try:
            if obj is False:
                if is_file:
                    return system_json.load(string)
                return system_json.loads(string, encoding='utf8')
            else:
                if is_file:
                    return system_json.load(
                        string,
                        object_hook=lambda d: namedtuple('j', d.keys())
                        (*d.values()), ensure_ascii=False, encoding='utf8')
                return system_json.loads(
                    string,
                    object_hook=lambda d: namedtuple('j', d.keys())
                    (*d.values()), encoding='utf8')
        except (Exception, BaseException) as error:
            try:
                if current_app.config['DEBUG']:
                    raise error
            except RuntimeError as flask_error:
                raise error
            return None
205125
def parse_json(filename):
    
    # Regular expression for comments
    comment_re = re.compile(
        '(^)?[^\S\n]*/(?:\*(.*?)\*/[^\S\n]*|/[^\n]*)($)?',
        re.DOTALL | re.MULTILINE
    )

    with open(filename) as f:
        content = ''.join(f.readlines())

        ## Looking for comments
        match = comment_re.search(content)
        while match:
            # single line comment
            content = content[:match.start()] + content[match.end():]
            match = comment_re.search(content)

        # Return json file
        return json.loads(content)
934893
def _json_safe(cls, value):
        """"""
        # Date
        if type(value) == date:
            return str(value)

        # Datetime
        elif type(value) == datetime:
            return value.strftime('%Y-%m-%d %H:%M:%S')

        # Object Id
        elif isinstance(value, ObjectId):
            return str(value)

        # Frame
        elif isinstance(value, _BaseFrame):
            return value.to_json_type()

        # Lists
        elif isinstance(value, (list, tuple)):
            return [cls._json_safe(v) for v in value]

        # Dictionaries
        elif isinstance(value, dict):
            return {k:cls._json_safe(v) for k, v in value.items()}

        return value
28750
def read_string(self, key, embedded=True):
        
        data = None
        if key is not None:
            key_type = self.variable_type(key)
            data = self.db.read(key.strip())
            if data is not None:
                # handle improperly saved string
                try:
                    data = json.loads(data)
                    if embedded:
                        data = self.read_embedded(data, key_type)
                    if data is not None:
                        # reverted the previous change where data was encoded due to issues where
                        # it broke the operator method in py3 (e.g. b'1' ne '1').
                        # data = str(data)
                        data = u'{}'.format(data)
                except ValueError as e:
                    err = u'Failed loading JSON data ({}). Error: ({})'.format(data, e)
                    self.tcex.log.error(err)
        else:
            self.tcex.log.warning(u'The key field was None.')
        return data
992944
function (str) {
    str = str.replace(/\s/g,'');
    if (!str.match(/^\{.*\}$/)) {
      throw new sjcl.exception.invalid("json decode: this isn't json!");
    }
    var a = str.replace(/^\{|\}$/g, '').split(/,/), out={}, i, m;
    for (i=0; i<a.length; i++) {
      if (!(m=a[i].match(/^\s*(?:(["']?)([a-z][a-z0-9]*)\1)\s*:\s*(?:(-?\d+)|"([a-z0-9+\/%*_.@=\-]*)"|(true|false))$/i))) {
        throw new sjcl.exception.invalid("json decode: this isn't json!");
      }
      if (m[3]) {
        out[m[2]] = parseInt(m[3],10);
      } else if (m[4]) {
        out[m[2]] = m[2].match(/^(ct|adata|salt|iv)$/) ? sjcl.codec.base64.toBits(m[4]) : unescape(m[4]);
      } else if (m[5]) {
        out[m[2]] = m[5] === 'true';
      }
    }
    return out;
  }
299229
def from_json(self, value):
        
        if value is None:
            return None

        if isinstance(value, six.binary_type):
            value = value.decode('utf-8')

        if isinstance(value, six.text_type):
            # Parser interprets empty string as now by default
            if value == "":
                return None
            try:
                value = dateutil.parser.parse(value)
            except (TypeError, ValueError):
                raise ValueError("Could not parse {} as a date".format(value))

        if not isinstance(value, datetime.datetime):
            raise TypeError(
                "Value should be loaded from a string, a datetime object or None, not {}".format(type(value))
            )

        if value.tzinfo is not None:  # pylint: disable=maybe-no-member
            return value.astimezone(pytz.utc)  # pylint: disable=maybe-no-member
        else:
            return value.replace(tzinfo=pytz.utc)
329323
def _is_valid_collection_json(self, json_repr):
        """"""
        collection = self._coerce_json_to_collection(json_repr)
        if collection is None:
            # invalid JSON, definitely broken
            return False
        aa = validate_collection(collection)
        errors = aa[0]
        for e in errors:
            _LOG.debug('> invalid JSON: {m}'.format(m=e.encode('utf-8')))
        if len(errors) > 0:
            return False
        return True
288133
def json_loads(data):
    
    try:
        return json.loads(data, encoding='utf-8')
    except TypeError:
        return json.loads(data.decode('utf-8'))
152812
def handle_json(json_str)
      begin
        req  = JSON::parse(json_str)
        resp = handle(req)
      rescue JSON::ParserError => e
        resp = err_resp({ }, -32700, "Unable to parse JSON: #{e.message}")
      end
      
      # Note the `:ascii_only` usage here. Important.
      return JSON::generate(resp, { :ascii_only=>true })
    end