本文整理匯總了Python中json.JSONDecoder方法的典型用法代碼示例。如果您正苦於以下問題:Python json.JSONDecoder方法的具體用法?Python json.JSONDecoder怎麽用?Python json.JSONDecoder使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類json
的用法示例。
在下文中一共展示了json.JSONDecoder方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get_api
# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecoder [as 別名]
def get_api(self, url):
# return the json version
get = None
get = self.get_raw(url)
if get != None:
try:
return json.JSONDecoder().decode(get)
except Exception as e:
self._error = "API response has invalid JSON format"
self._error_msg = str(e.reason)
self._update_ready = None
return None
else:
return None
# create a working directory and download the new files
示例2: __init__
# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecoder [as 別名]
def __init__(self, encoding='utf-8', skipkeys=False, ensure_ascii=True,
check_circular=True, allow_nan=True, sort_keys=True, indent=None,
separators=None, strict=True):
self._text_encoding = encoding
if separators is None:
# ensure separators are explicitly specified, and consistent behaviour across
# Python versions, and most compact representation if indent is None
if indent is None:
separators = ',', ':'
else:
separators = ', ', ': '
separators = tuple(separators)
self._encoder_config = dict(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
check_circular=check_circular, allow_nan=allow_nan,
indent=indent, separators=separators,
sort_keys=sort_keys)
self._encoder = _json.JSONEncoder(**self._encoder_config)
self._decoder_config = dict(strict=strict)
self._decoder = _json.JSONDecoder(**self._decoder_config)
示例3: json_loads
# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecoder [as 別名]
def json_loads(data):
"""
It works as json.loads but supporting multiple encodings in the same
string and accepting an `str` parameter that won't be converted to unicode.
:param data: the string to load the objects from
:type data: str
:returns: the corresponding python object result of parsing 'data', this
behaves similarly as json.loads, with the exception of that
returns always `str` instead of `unicode`.
"""
obj = None
with CustomJsonScanner():
# We need to use the cls parameter in order to trigger the code
# that will let us control the string parsing method.
obj = json.loads(data, cls=json.JSONDecoder)
return obj
示例4: readJSONString
# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecoder [as 別名]
def readJSONString(self, skipContext):
string = []
if skipContext is False:
self.context.read()
self.readJSONSyntaxChar(QUOTE)
while True:
character = self.reader.read()
if character == QUOTE:
break
if character == ESCSEQ[0]:
character = self.reader.read()
if character == ESCSEQ[1]:
self.readJSONSyntaxChar(ZERO)
self.readJSONSyntaxChar(ZERO)
character = json.JSONDecoder().decode('"\u00%s"' % self.trans.read(2))
else:
off = ESCAPE_CHAR.find(character)
if off == -1:
raise TProtocolException(TProtocolException.INVALID_DATA,
"Expected control char")
character = ESCAPE_CHAR_VALS[off]
string.append(character)
return ''.join(string)
示例5: __decode_json_stream
# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecoder [as 別名]
def __decode_json_stream(document, pos=0, decoder=json.JSONDecoder()):
while True:
# Create json stream without whitespace
match = NOT_WHITESPACE.search(document, pos)
if not match:
# No more data
return
pos = match.start()
try:
obj, pos = decoder.raw_decode(document, pos)
except json.JSONDecodeError:
raise Exception("Invalid json formatting")
yield obj
示例6: object_hook
# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecoder [as 別名]
def object_hook(self, object_dict):
""" Hook which when passed into a json.JSONDecoder will replace each dict
in a json string with its index and convert the dict to an object as defined
by the passed in condition_decoder. The newly created condition object is
appended to the conditions_list.
Args:
object_dict: Dict representing an object.
Returns:
An index which will be used as the placeholder in the condition_structure
"""
instance = self.decoder(object_dict)
self.condition_list.append(instance)
self.index += 1
return self.index
示例7: loads
# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecoder [as 別名]
def loads(conditions_string):
""" Deserializes the conditions property into its corresponding
components: the condition_structure and the condition_list.
Args:
conditions_string: String defining valid and/or conditions.
Returns:
A tuple of (condition_structure, condition_list).
condition_structure: nested list of operators and placeholders for operands.
condition_list: list of conditions whose index correspond to the values of the placeholders.
"""
decoder = ConditionDecoder(_audience_condition_deserializer)
# Create a custom JSONDecoder using the ConditionDecoder's object_hook method
# to create the condition_structure as well as populate the condition_list
json_decoder = json.JSONDecoder(object_hook=decoder.object_hook)
# Perform the decoding
condition_structure = json_decoder.decode(conditions_string)
condition_list = decoder.condition_list
return (condition_structure, condition_list)
示例8: dimod_object_hook
# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecoder [as 別名]
def dimod_object_hook(obj):
"""JSON-decoding for dimod objects.
See Also:
:class:`json.JSONDecoder` for using custom decoders.
"""
if _is_sampleset_v2(obj):
# in the future we could handle subtypes but right now we just have the
# one
return SampleSet.from_serializable(obj)
elif _is_bqm(obj):
# in the future we could handle subtypes but right now we just have the
# one
return BinaryQuadraticModel.from_serializable(obj)
return obj
示例9: _variable_export_helper
# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecoder [as 別名]
def _variable_export_helper(filepath):
"""Helps export all of the variables to the file"""
var_dict = {}
with create_session() as session:
qry = session.query(Variable).all()
data = json.JSONDecoder()
for var in qry:
try:
val = data.decode(var.val)
except Exception: # pylint: disable=broad-except
val = var.val
var_dict[var.key] = val
with open(filepath, 'w') as varfile:
varfile.write(json.dumps(var_dict, sort_keys=True, indent=4))
print("{} variables successfully exported to {}".format(len(var_dict), filepath))
示例10: test_logs_for_status
# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecoder [as 別名]
def test_logs_for_status(bep_file, status):
targets = []
with open(bep_file, encoding="utf-8") as f:
raw_data = f.read()
decoder = json.JSONDecoder()
pos = 0
while pos < len(raw_data):
try:
bep_obj, size = decoder.raw_decode(raw_data[pos:])
except ValueError as e:
eprint("JSON decoding error: " + str(e))
return targets
if "testSummary" in bep_obj:
test_target = bep_obj["id"]["testSummary"]["label"]
test_status = bep_obj["testSummary"]["overallStatus"]
if test_status in status:
outputs = bep_obj["testSummary"]["failed"]
test_logs = []
for output in outputs:
test_logs.append(url2pathname(urlparse(output["uri"]).path))
targets.append((test_target, test_logs))
pos += size + 1
return targets
示例11: getPlayUrl
# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecoder [as 別名]
def getPlayUrl (self, taskID) :
taskID = str(taskID)
bdApi = 'https://yun.baidu.com/rest/2.0/services/cloud_dl?need_task_info=1&status=255&start=0&limit=10&method=list_task&app_id=250528&channel=chunlei&web=1&app_id=250528&bdstoken={}&clienttype=0'.format(self.bdInfo['token'])
html = self.Tools.getPage(bdApi, self.requestHeader)
if html['code'] == '200' :
body = html['body']
else :
body = html['body']
info = json.JSONDecoder().decode(body)
taskInfo = info['task_info']
try:
for x in taskInfo :
if taskID == x['task_id'] :
savePath = urllib.parse.quote(x['save_path'].encode("UTF8"))
playUrl = 'https://yun.baidu.com/play/video#video/path=' + savePath
break
except Exception as e:
playUrl = ''
return (playUrl)
示例12: get_pm25
# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecoder [as 別名]
def get_pm25():
global weather_url
req = urllib2.Request(weather_url)
resp = urllib2.urlopen(req)
content = resp.read()
if(content):
weatherJSON = json.JSONDecoder().decode(content)
#print(content)
try:
if weatherJSON['HeWeather data service 3.0'][0]['status'] == "ok":
if weatherJSON['HeWeather data service 3.0'][0].has_key('aqi'):
print(weatherJSON['HeWeather data service 3.0'][0]['aqi']['city']['pm25'])
return int(weatherJSON['HeWeather data service 3.0'][0]['aqi']['city']['pm25'])
else:
return -1
else:
return -1
except:
return -1
示例13: get_pm25
# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecoder [as 別名]
def get_pm25():
global weather_url
req = urllib2.Request(weather_url)
resp = urllib2.urlopen(req, timeout = 5)
content = resp.read()
if(content):
weatherJSON = json.JSONDecoder().decode(content)
#print(content)
try:
if weatherJSON['HeWeather data service 3.0'][0]['status'] == "ok":
if weatherJSON['HeWeather data service 3.0'][0].has_key('aqi'):
print(weatherJSON['HeWeather data service 3.0'][0]['aqi']['city']['pm25'])
return int(weatherJSON['HeWeather data service 3.0'][0]['aqi']['city']['pm25'])
else:
return -1
else:
return -1
except:
return -1
示例14: get_city_temp
# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecoder [as 別名]
def get_city_temp():
global weather_url
req = urllib2.Request(weather_url)
resp = urllib2.urlopen(req, timeout = 5)
content = resp.read()
if(content):
weatherJSON = json.JSONDecoder().decode(content)
#print(content)
try:
if weatherJSON['HeWeather data service 3.0'][0]['status'] == "ok":
if weatherJSON['HeWeather data service 3.0'][0].has_key('now'):
print(weatherJSON['HeWeather data service 3.0'][0]['now']['tmp'])
return int(weatherJSON['HeWeather data service 3.0'][0]['now']['tmp'])
else:
return -128
else:
return -128
except:
return -128
示例15: __init__
# 需要導入模塊: import json [as 別名]
# 或者: from json import JSONDecoder [as 別名]
def __init__(self, **kw_args):
"""Compose the standard JSONDecoder with a custom object_hook.
The custom object_hook will recognize a dictionary that represents
a ClientData object, and decode it as a ClientData object. All other
objects will get passed to the standard JSONDecoder.
Args:
Same arguments as JSONDecoder.__init__() with the exception that
'strict' is always set to False. If an 'object_hook' is supplied
then it will be called by _object_decode() if the object is
not interpreted as ClientData.
"""
self._other_object_hook = None
kw_args_new = kw_args.copy()
if 'object_hook' in kw_args:
self._other_object_hook = kw_args['object_hook']
kw_args_new['object_hook'] = self._object_decode
# Note: strict=False because the notes attribute might contain
# line feeds.
#
kw_args_new['strict'] = False
self._decoder = json.JSONDecoder(**kw_args_new)