Python simplejson.loads() Examples
The following are 30
code examples of simplejson.loads().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
simplejson
, or try the search function
.
Example #1
Source File: test_decode.py From qgis-cartodb with GNU General Public License v2.0 | 6 votes |
def test_object_pairs_hook(self): s = '{"xkd":1, "kcw":2, "art":3, "hxm":4, "qrt":5, "pad":6, "hoy":7}' p = [("xkd", 1), ("kcw", 2), ("art", 3), ("hxm", 4), ("qrt", 5), ("pad", 6), ("hoy", 7)] self.assertEqual(json.loads(s), eval(s)) self.assertEqual(json.loads(s, object_pairs_hook=lambda x: x), p) self.assertEqual(json.load(StringIO(s), object_pairs_hook=lambda x: x), p) od = json.loads(s, object_pairs_hook=OrderedDict) self.assertEqual(od, OrderedDict(p)) self.assertEqual(type(od), OrderedDict) # the object_pairs_hook takes priority over the object_hook self.assertEqual(json.loads(s, object_pairs_hook=OrderedDict, object_hook=lambda x: None), OrderedDict(p))
Example #2
Source File: test_namedtuple.py From qgis-cartodb with GNU General Public License v2.0 | 6 votes |
def test_namedtuple_dump(self): for v in [Value(1), Point(1, 2), DuckValue(1), DuckPoint(1, 2)]: d = v._asdict() sio = StringIO() json.dump(v, sio) self.assertEqual(d, json.loads(sio.getvalue())) sio = StringIO() json.dump(v, sio, namedtuple_as_object=True) self.assertEqual( d, json.loads(sio.getvalue())) sio = StringIO() json.dump(v, sio, tuple_as_array=False) self.assertEqual(d, json.loads(sio.getvalue())) sio = StringIO() json.dump(v, sio, namedtuple_as_object=True, tuple_as_array=False) self.assertEqual( d, json.loads(sio.getvalue()))
Example #3
Source File: tb_updater.py From thingsboard-gateway with Apache License 2.0 | 6 votes |
def check_for_new_version(self): log.debug("Checking for new version") request_args = self.form_request_params() try: response = post(**request_args) content = None content = loads(response.content) if content is not None and content.get("updateAvailable", False): new_version = content["message"].replace("New version ", "").replace(" is available!", "") if new_version > self.__version["current_version"]: log.info(content["message"]) self.__version["latest_version"] = new_version log.info("\n\n[===UPDATE===]\n\n New version %s is available! \n\n[===UPDATE===]\n", self.__version["latest_version"]) except ConnectionRefusedError: log.warning("Cannot connect to the update service. PLease check your internet connection.") except Exception as e: log.exception(e)
Example #4
Source File: __init__.py From bugbuzz-python with MIT License | 6 votes |
def _request_sync(self, request, timeout=5): global _urllib_request ## Build URL url = self.getUrl(request) ## Send Request Expecting JSONP Response response = _urllib_request(url, timeout=timeout) try: resp_json = json.loads(response[0]) except ValueError: return [0, "JSON Error"] if response[1] != 200 and 'message' in resp_json and 'payload' in resp_json: return {'message': resp_json['message'], 'payload': resp_json['payload']} if response[1] == 0: return [0, resp_json] return resp_json
Example #5
Source File: cartodbapi.py From qgis-cartodb with GNU General Public License v2.0 | 6 votes |
def returnFetchContent(self, reply): response = str(reply.readAll()) # qDebug('Response:' + response) # qDebug('Error: ' + str(reply.error())) # qDebug('Status: ' + str(reply.rawHeader('Location'))) if reply.rawHeader('Location') == 'http://cartodb.com/noneuser.html' or \ reply.rawHeader('Location') == 'http://carto.com/noneuser.html': response = '{"error": "User not found"}' elif reply.error() == QNetworkReply.AuthenticationRequiredError: response = '{"error": "Confirm user credentials"}' if self.returnDict: try: self.fetchContent.emit(json.loads(response)) except ValueError as e: qDebug('Error loading json. {}'.format(response)) response = '{"error": "Error loading JSON data"}' self.fetchContent.emit(json.loads(response)) else: self.fetchContent.emit(response)
Example #6
Source File: test_ujson.py From recruit with Apache License 2.0 | 6 votes |
def test_encode_string_conversion(self, ensure_ascii): string_input = "A string \\ / \b \f \n \r \t </script> &" not_html_encoded = ('"A string \\\\ \\/ \\b \\f \\n ' '\\r \\t <\\/script> &"') html_encoded = ('"A string \\\\ \\/ \\b \\f \\n \\r \\t ' '\\u003c\\/script\\u003e \\u0026"') def helper(expected_output, **encode_kwargs): output = ujson.encode(string_input, ensure_ascii=ensure_ascii, **encode_kwargs) assert output == expected_output assert string_input == json.loads(output) assert string_input == ujson.decode(output) # Default behavior assumes encode_html_chars=False. helper(not_html_encoded) # Make sure explicit encode_html_chars=False works. helper(not_html_encoded, encode_html_chars=False) # Make sure explicit encode_html_chars=True does the encoding. helper(html_encoded, encode_html_chars=True)
Example #7
Source File: __init__.py From bugbuzz-python with MIT License | 6 votes |
def _request_sync(self, request, timeout=5): global _urllib_request ## Build URL url = self.getUrl(request) ## Send Request Expecting JSONP Response response = _urllib_request(url, timeout=timeout) try: resp_json = json.loads(response[0]) except ValueError: return [0, "JSON Error"] if response[1] != 200 and 'message' in resp_json and 'payload' in resp_json: return {'message': resp_json['message'], 'payload': resp_json['payload']} if response[1] == 0: return [0, resp_json] return resp_json
Example #8
Source File: test_unicode.py From qgis-cartodb with GNU General Public License v2.0 | 6 votes |
def test_invalid_escape_sequences(self): # incomplete escape sequence self.assertRaises(json.JSONDecodeError, json.loads, '"\\u') self.assertRaises(json.JSONDecodeError, json.loads, '"\\u1') self.assertRaises(json.JSONDecodeError, json.loads, '"\\u12') self.assertRaises(json.JSONDecodeError, json.loads, '"\\u123') self.assertRaises(json.JSONDecodeError, json.loads, '"\\u1234') # invalid escape sequence self.assertRaises(json.JSONDecodeError, json.loads, '"\\u123x"') self.assertRaises(json.JSONDecodeError, json.loads, '"\\u12x4"') self.assertRaises(json.JSONDecodeError, json.loads, '"\\u1x34"') self.assertRaises(json.JSONDecodeError, json.loads, '"\\ux234"') if sys.maxunicode > 65535: # invalid escape sequence for low surrogate self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\u"') self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\u0"') self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\u00"') self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\u000"') self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\u000x"') self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\u00x0"') self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\u0x00"') self.assertRaises(json.JSONDecodeError, json.loads, '"\\ud800\\ux000"')
Example #9
Source File: shadowserver.py From threat_intel with MIT License | 6 votes |
def __init__(self, cache_file_name=None, update_cache=True, req_timeout=90.0): """Establishes basic HTTP params and loads a cache. Args: cache_file_name: String file name of cache. update_cache: Determines whether cache should be written out back to the disk when closing it. Default is `True`. req_timeout: Maximum number of seconds to wait without reading a response byte before deciding an error has occurred. Default is 90.0 seconds. """ # TODO - lookup request rate limit # By observation, ShadowServer can be quite slow, so give it 90 seconds before it times out. self._requests = MultiRequest(max_requests=2, req_timeout=req_timeout) # Create an ApiCache if instructed to self._cache = ApiCache(cache_file_name, update_cache) if cache_file_name else None
Example #10
Source File: models.py From gazetteer with MIT License | 6 votes |
def get_geojson(self, srid=4326): geom = json.loads(self.geometry.transform(srid, True).geojson) if self.feature_type is None: feature_type = '' else: feature_type = self.feature_type.name properties = { 'id': self.id, 'uri': self.url, 'preferred_name': self.preferred_name, 'feature_type': feature_type, 'admin1': self.admin1, 'admin2': self.admin2 } return { 'type': 'Feature', 'properties': properties, 'geometry': geom }
Example #11
Source File: test_bitsize_int_as_string.py From qgis-cartodb with GNU General Public License v2.0 | 5 votes |
def test_dict_keys(self): for val, _ in self.values: expect = {str(val): 'value'} val = {val: 'value'} self.assertEqual( expect, json.loads(json.dumps(val))) self.assertEqual( expect, json.loads(json.dumps(val, int_as_string_bitcount=31)))
Example #12
Source File: test_ujson.py From recruit with Apache License 2.0 | 5 votes |
def test_encode_double_conversion(self, double_input): output = ujson.encode(double_input) assert round(double_input, 5) == round(json.loads(output), 5) assert round(double_input, 5) == round(ujson.decode(output), 5)
Example #13
Source File: test_decode.py From qgis-cartodb with GNU General Public License v2.0 | 5 votes |
def test_keys_reuse_str(self): s = u'[{"a_key": 1, "b_\xe9": 2}, {"a_key": 3, "b_\xe9": 4}]'.encode('utf8') self.check_keys_reuse(s, json.loads)
Example #14
Source File: test_ujson.py From recruit with Apache License 2.0 | 5 votes |
def test_double_precision(self): double_input = 30.012345678901234 output = ujson.encode(double_input, double_precision=15) assert double_input == json.loads(output) assert double_input == ujson.decode(output) for double_precision in (3, 9): output = ujson.encode(double_input, double_precision=double_precision) rounded_input = round(double_input, double_precision) assert rounded_input == json.loads(output) assert rounded_input == ujson.decode(output)
Example #15
Source File: test_ujson.py From recruit with Apache License 2.0 | 5 votes |
def test_encode_array_of_doubles(self): doubles_input = [31337.31337, 31337.31337, 31337.31337, 31337.31337] * 10 output = ujson.encode(doubles_input) assert doubles_input == json.loads(output) assert doubles_input == ujson.decode(output) tm.assert_numpy_array_equal(np.array(doubles_input), ujson.decode(output, numpy=True))
Example #16
Source File: test_bitsize_int_as_string.py From qgis-cartodb with GNU General Public License v2.0 | 5 votes |
def test_lists(self): for val, expect in self.values: val = [val, val] expect = [expect, expect] self.assertEqual( val, json.loads(json.dumps(val))) self.assertEqual( expect, json.loads(json.dumps(val, int_as_string_bitcount=31)))
Example #17
Source File: test_bitsize_int_as_string.py From qgis-cartodb with GNU General Public License v2.0 | 5 votes |
def test_ints(self): for val, expect in self.values: self.assertEqual( val, json.loads(json.dumps(val))) self.assertEqual( expect, json.loads(json.dumps(val, int_as_string_bitcount=31)), )
Example #18
Source File: test_bitsize_int_as_string.py From qgis-cartodb with GNU General Public License v2.0 | 5 votes |
def test_ints_outside_range_fails(self): self.assertNotEqual( str(1 << 15), json.loads(json.dumps(1 << 15, int_as_string_bitcount=16)), )
Example #19
Source File: test_ujson.py From recruit with Apache License 2.0 | 5 votes |
def test_encode_string_conversion2(self): string_input = "A string \\ / \b \f \n \r \t" output = ujson.encode(string_input) assert string_input == json.loads(output) assert string_input == ujson.decode(output) assert output == '"A string \\\\ \\/ \\b \\f \\n \\r \\t"'
Example #20
Source File: test_ujson.py From recruit with Apache License 2.0 | 5 votes |
def test_encode_non_c_locale(self): lc_category = locale.LC_NUMERIC # We just need one of these locales to work. for new_locale in ("it_IT.UTF-8", "Italian_Italy"): if tm.can_set_locale(new_locale, lc_category): with tm.set_locale(new_locale, lc_category): assert ujson.loads(ujson.dumps(4.78e60)) == 4.78e60 assert ujson.loads("4.78", precise_float=True) == 4.78 break
Example #21
Source File: test_for_json.py From qgis-cartodb with GNU General Public License v2.0 | 5 votes |
def assertRoundTrip(self, obj, other, for_json=True): if for_json is None: # None will use the default s = json.dumps(obj) else: s = json.dumps(obj, for_json=for_json) self.assertEqual( json.loads(s), other)
Example #22
Source File: test_decode.py From qgis-cartodb with GNU General Public License v2.0 | 5 votes |
def test_empty_strings(self): self.assertEqual(json.loads('""'), "") self.assertEqual(json.loads(u'""'), u"") self.assertEqual(json.loads('[""]'), [""]) self.assertEqual(json.loads(u'[""]'), [u""])
Example #23
Source File: test_fail.py From qgis-cartodb with GNU General Public License v2.0 | 5 votes |
def test_failures(self): for idx, doc in enumerate(JSONDOCS): idx = idx + 1 if idx in SKIPS: json.loads(doc) continue try: json.loads(doc) except json.JSONDecodeError: pass else: self.fail("Expected failure for fail%d.json: %r" % (idx, doc))
Example #24
Source File: test_decode.py From qgis-cartodb with GNU General Public License v2.0 | 5 votes |
def check_keys_reuse(self, source, loads): rval = loads(source) (a, b), (c, d) = sorted(rval[0]), sorted(rval[1]) self.assertIs(a, c) self.assertIs(b, d)
Example #25
Source File: test_decode.py From qgis-cartodb with GNU General Public License v2.0 | 5 votes |
def test_empty_objects(self): s = '{}' self.assertEqual(json.loads(s), eval(s)) s = '[]' self.assertEqual(json.loads(s), eval(s)) s = '""' self.assertEqual(json.loads(s), eval(s))
Example #26
Source File: test_decode.py From qgis-cartodb with GNU General Public License v2.0 | 5 votes |
def test_decoder_optimizations(self): # Several optimizations were made that skip over calls to # the whitespace regex, so this test is designed to try and # exercise the uncommon cases. The array cases are already covered. rval = json.loads('{ "key" : "value" , "k":"v" }') self.assertEqual(rval, {"key":"value", "k":"v"})
Example #27
Source File: test_decode.py From qgis-cartodb with GNU General Public License v2.0 | 5 votes |
def test_decimal(self): rval = json.loads('1.1', parse_float=decimal.Decimal) self.assertTrue(isinstance(rval, decimal.Decimal)) self.assertEqual(rval, decimal.Decimal('1.1'))
Example #28
Source File: test_errors.py From qgis-cartodb with GNU General Public License v2.0 | 5 votes |
def test_error_is_pickable(self): err = None try: json.loads('{}\na\nb') except json.JSONDecodeError: err = sys.exc_info()[1] else: self.fail('Expected JSONDecodeError') s = pickle.dumps(err) e = pickle.loads(s) self.assertEqual(err.msg, e.msg) self.assertEqual(err.doc, e.doc) self.assertEqual(err.pos, e.pos) self.assertEqual(err.end, e.end)
Example #29
Source File: test_errors.py From qgis-cartodb with GNU General Public License v2.0 | 5 votes |
def test_scan_error(self): err = None for t in (u, b): try: json.loads(t('{"asdf": "')) except json.JSONDecodeError: err = sys.exc_info()[1] else: self.fail('Expected JSONDecodeError') self.assertEqual(err.lineno, 1) self.assertEqual(err.colno, 10)
Example #30
Source File: test_errors.py From qgis-cartodb with GNU General Public License v2.0 | 5 votes |
def test_decode_error(self): err = None try: json.loads('{}\na\nb') except json.JSONDecodeError: err = sys.exc_info()[1] else: self.fail('Expected JSONDecodeError') self.assertEqual(err.lineno, 2) self.assertEqual(err.colno, 1) self.assertEqual(err.endlineno, 3) self.assertEqual(err.endcolno, 2)