本文整理汇总了Python中xml2json.xml2json函数的典型用法代码示例。如果您正苦于以下问题:Python xml2json函数的具体用法?Python xml2json怎么用?Python xml2json使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了xml2json函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: compare_sets
def compare_sets(file_list):
comparison_list = comparison_tuples(file_list)
for tuple in comparison_list:
print tuple
past_xml, current_xml = open_xml(tuple)
past_dict = json.loads(xml2json(past_xml, 0, 1))
current_dict = json.loads(xml2json(current_xml, 0, 1))
differ = DictDiffer(current_dict['Ableton']['LiveSet']['Tracks'], past_dict['Ableton']['LiveSet']['Tracks'])
print "ADDED"
print json.dumps(differ.added(), indent=4)
print "REMOVED"
print json.dumps(differ.removed(), indent=4)
print "CHANGED"
print json.dumps(differ.changed(), indent=4)
示例2: get
def get(self):
if not self.request.get('ean'):
return
id_type = 'EAN'
ean = self.request.get('ean')
if len(ean) <13:
id_type = 'ISBN'
with open("amazon.yml", "r") as config_file:
amazon_credentials = yaml.load(config_file)
amazon = amazonproduct.api.API(*[amazon_credentials.get(k)
for k in ("access_key","secret_key", "locale", "associate_tag")], processor=string_response_parser)
#node = amazon.item_search('Books', Publisher='Galileo Press')"
#node = amazon.item_lookup('9781593271190',SearchIndex='Books', IdType="EAN", ResponseGroup="Large")
node = amazon.item_lookup(ean, SearchIndex='Books', IdType=id_type, ResponseGroup="Small,Reviews,Images")
self.response.headers.add_header('Content-Type',"application/json; charset=utf-8")
self.response.headers.add_header('Connection',"close")
js_string = xml2json.xml2json(node)
# The xml tree will have the schema url in the tags, which we don't want
js_string = re.sub(r'\{http.*?\}','',js_string)
self.response.out.write(js_string)
logging.info(type(self.response))
logging.info(type(self.response.out))
示例3: post
def post(self):
self.set_header("Content-Type", "application/json")
print self.request.body
json_data = xml2json(self.request.body.encode('utf8'), options)
data = json.loads(json_data)['xml']
return_code = data['return_code']
if return_code == 'SUCCESS':
openid = data['openid']
out_trade_no = data['out_trade_no']
cash_fee = data['cash_fee']
where = " openid='%s' and id=%s and (status<>'payed' or status is null) " % (openid, out_trade_no)
from webpy_db import SQLLiteral
count = pg.update('pay', status='payed', wexin_return=json_data, stat_date=SQLLiteral('NOW()'), where=where)
if count != 1:
error_info = 'update failure: count=%s where=%s' % (count, where)
print error_info
raise Exception(error_info)
else:
wechat = wechat_oper.getWechat()
content = '''您支付的 %s 元已进入充值系统,正在向您的油卡充值,请耐心等候......''' % (int(cash_fee) / 100.00)
wechat.send_text_message(openid, content)
else:
print data['return_msg']
#{u'openid': u'oGXiIwHwx_zB8ekXibYjdt3Xb_fE', u'trade_type': u'JSAPI', u'cash_fee': u'1', u'nonce_str': u'798243e4902342c83e833c71141385f', u'return_code': u'SUCCESS', u'is_subscribe': u'Y', u'bank_type': u'CFT', u'mch_id': u'1308443701', u'out_trade_no': u'86', u'result_code': u'SUCCESS', u'total_fee': u'1', u'appid': u'wx907d8a3f50de65db', u'fee_type': u'CNY', u'time_end': u'20160215113326', u'transaction_id': u'1002230516201602153283628055', u'sign': u'CAD12073F45232BB600B8F066B434A30'}
success = '''
<xml>
<return_code><![CDATA[SUCCESS]]></return_code>
<return_msg><![CDATA[OK]]></return_msg>
</xml>
'''
self.write(success)
示例4: get_acl_ont
def get_acl_ont(rest_epr,ont_id):
content=http_request(rest_epr+ "virtual/ontology/"+ont_id,dict(),API_KEY_AUTH)
ont = json.loads(xml2json.xml2json(content))
try:
return ont["success"]["data"]["ontologyBean"]["userAcl"]
except KeyError, k:
return None
示例5: post
def post(self, resource_uri, content):
"""
``POST``s a resource by its internal API URI and contents.
"""
# Attempt to retrieve the response
try:
response_header, response_content = self.request("%s%s" %
(self._xero_api_url,
resource_uri),
method="POST",
body=urllib.urlencode({"xml": content}))
except:
raise XeroClientRequestException
# Check if there is an error:
if response_header["status"] == "400":
raise XeroClientBadRequestException(response_content)
elif response_header["status"] == "404":
raise XeroClientNotFoundException()
elif response_header["status"] == "501":
raise XeroClientNotImplementedException(response_content)
elif response_header["status"] != "200":
raise XeroClientUnknownException(response_content)
# Convert the data into a JSON object:
json_string = xml2json.xml2json(response_content)
# Convert the json_string to a Python dictionary and return:
return json.loads(json_string)
示例6: xml_collections_endpoint
def xml_collections_endpoint(**lookup):
resource = _resource()
response = None
method = request_method()
if request.content_type.endswith("/xml"):
if method == "POST":
# response = post(resource, payl=xml2json(request.data))
response = post_internal(resource,
payl=xml2json(request.data),
skip_validation=True)
elif method == "GET":
response = collections_endpoint(**lookup)
l = json.loads(response.data.decode('utf-8'))['_items']
response.data = xmltodict.unparse({
'gdxp': {
"supplier": list(map(popper, l))
}
})
else:
raise NotImplementedError('Not implemented')
return send_response(resource, response)
else:
return collections_endpoint(**lookup)
示例7: __init__
def __init__(self, xml):
"""
:param xml: 支付成功回调的XML
"""
self.xml = xml
options = optparse.Values({"pretty": False})
self.xml_json = json.loads(xml2json(self.xml, options))['xml']
self.sign = self.xml_json.get('sign', '')
示例8: main
def main():
p = optparse.OptionParser(
description='Converts Maven metadata XML file to Cohorte Website latest.json JSON file.',
prog='latest',
usage='%prog -o file.json [url]'
)
p.add_option('--out', '-o', help="Write to OUT instead of stdout")
options, arguments = p.parse_args()
#input = inputstream.read()
fp = urllib2.urlopen(arguments[0])
input = fp.read()
options.pretty = True
out = xml2json.xml2json(input, options, 1, 1)
final = {}
k = arguments[0].rfind("/")
url_path = arguments[0][:k]
final["snapshots"] = {}
final["releases"] = {}
# generate cohorte file
json_data = json.loads(out)
artifactId = json_data["metadata"]["artifactId"]
accepted_extensions = ['zip', 'tar.gz', 'jar']
for i in json_data["metadata"]["versioning"]["snapshotVersions"]["snapshotVersion"]:
if any(i["extension"] in s for s in accepted_extensions):
if i["extension"] == "jar":
suffix = ""
else:
suffix = "-" + i["classifier"]
name = artifactId + suffix
if name in final["snapshots"].keys():
# add file only
extension = i["extension"]
version = i["value"]
file_name = artifactId + "-" + version + suffix + "." + extension
final["snapshots"][name]["files"][extension] = url_path + "/" + file_name
else:
# create new entry
extension = i["extension"]
version = i["value"]
file_name = artifactId + "-" + version + suffix + "." + extension
final["snapshots"][name] = {}
final["snapshots"][name]["version"] = version
final["snapshots"][name]["files"] = {}
final["snapshots"][name]["files"][extension] = url_path + "/" + file_name
if (options.out):
file = open(options.out, 'w')
file.write(json.dumps(final, sort_keys=True, indent=2, separators=(',', ': ')))
file.close()
else:
print(out)
示例9: get_devices
def get_devices(soup):
# Return all the devices in a set
out = []
tracks = [track for track in soup.find('tracks').children if track != '\n']
for track in tracks:
devices = [device for device in track.find('devices').children if device != '\n']
device_dicts = [json.loads(xml2json(str(device), 0, 1)) for device in devices]
[out.append(device_dict) for device_dict in device_dicts]
return out
示例10: get_ligands
def get_ligands(cfg,item):
try:
req = urllib2.Request('http://www.rcsb.org/pdb/rest/ligandInfo?structureId=%s' % item)
f = urllib2.urlopen(req)
result = f.read()
json_string = json.loads(xml2json.xml2json(result,optparse.Values({"pretty": False}),0))
return json_string
except:
return None
示例11: xml2mongo
def xml2mongo(filename, db):
# insert xml metadata into mongoDB
try:
with open(filename) as fin:
jout = xml2json.xml2json(fin.read())
# remove unnecessary enclosing tags, and convert into mongoDB default format
jout = re.subn(r"(?<=\})\,\s+(?=\{\"\_id)", "\n", jout[24:len(jout)-3])[0]
for doc in jout.split('\n'):
db.metadata.insert(json.loads(doc))
print "Collection 'metadata' is successfully inserted into 'HTRC' database."
示例12: download
def download(self):
if DEBUG:
raw = open(self.name + '.xml').read()
else:
self.log.info("%s begins to download xml" % self.name)
raw = requests.get(self.api).content
self.log.info("%s download xml finished %d" % (
self.name, len(raw)))
self.json = json.loads(xml2json(raw))
assert self.json
示例13: test_default_namespace_attribute
def test_default_namespace_attribute(self):
strip_ns = 0
json_string = xml2json.xml2json(xmlstring,options,strip_ns)
# check string
self.assertTrue(json_string.find("{http://www.w3.org/TR/html4/}table") != -1)
self.assertTrue(json_string.find("{http://www.w3.org/TR/html4/}tr") != -1)
self.assertTrue(json_string.find("@class") != -1)
# check the simple name is not exist
json_data = json.loads(json_string)
self.assertFalse("table" in json_data["root"])
示例14: convert_xform_to_json
def convert_xform_to_json(xml_string):
"""
takes xform payload as xml_string and returns the equivalent json
i.e. the json that will show up as xform.form
"""
try:
name, json_form = xml2json.xml2json(xml_string)
except xml2json.XMLSyntaxError as e:
raise couchforms.XMLSyntaxError(u'Invalid XML: %s' % e)
json_form['#type'] = name
return json_form
示例15: make_set_file
def make_set_file(file_list):
out = []
for file in file_list:
#print file
f = open(file, 'r')
xml = f.read()
#print xml
try:
dict =json.loads(xml2json(xml, 0, 1))
dict['@XMLFilename'] = file
out.append(dict)
except Exception as e:
print e
return out