<p>在测试开发过程中经常遇到各种存储格式的数据转换,前面也写了几篇小文。所以这里把它整合一下。</p>
<h3>一.python 下xml和dict相互转化,含attributes</h3>
<p>我们写测试用例或者配置文件很多都是用xml文件来存储,但是数据要在程序中被使用,还是拿dict来用比较方便,所以有必要掌握xml转换为dict的技巧。互转程序片段如下:</p>
<p>from lxml import etree</p>
<p>def dictlist(node):<br>
res = {}<br>
res[node.tag] = []<br>
xmltodict(node,res[node.tag])<br>
reply = {}<br>
reply[node.tag] = {'value':res[node.tag],'attributes':node.attrib}<br><br>
return reply</p>
<p>def xmltodict(node,res):<br>
rep = {}<br><br>
if len(node):<br>
#n = 0<br>
for n in list(node):<br>
rep[node.tag] = []<br>
value = xmltodict(n,rep[node.tag])<br>
if len(n):<br><br>
value = {'value':rep[node.tag],'attributes':n.attrib}<br>
#print value<br>
res.append({n.tag:value})<br>
else :<br>
#print rep[node.tag][0]<br>
res.append(rep[node.tag][0])<br><br>
else:<br>
value = {}<br>
value = {'value':node.text,'attributes':node.attrib}<br>
#print value<br>
res.append({node.tag:value})<br><br>
return <br>
def fromstring(strdict=None):<br>
root = etree.fromstring(strdict)<br>
return dictlist(root)</p>
<p>def parse(filename=None):<br>
tree = etree.parse(filename)<br>
return dictlist(tree.getroot())</p>
<p>
def main():<br>
tree = etree.parse('test.xml')<br>
print tree<br>
res = dictlist(tree.getroot())<br>
print res<br><br>
def dict2xml(d):<br>
from xml.sax.saxutils import escape<br>
def unicodify(o):<br>
if o is None:<br>
return u'';<br>
return unicode(o)<br>
lines = ["<?xml version=/"1.0/" encoding=/"utf-8/"?>"]<br>
def addDict(node, offset):<br>
for name, value in node.iteritems():<br>
if name == "attributes":<br>
strqq = lines[len(lines)-1]<br>
index = strqq.find(u"<")<br>
strqq = strqq[index+1:len(strqq)-1]<br>
for x,y in value.iteritems():<br>
strqq = strqq + u" " *4 + u"%s='%s'"%(x,y)<br>
lines[len(lines)-1] = u" " * index + u"<%s>"%(strqq)<br>
else:<br>
if isinstance(value, dict):<br>
lines.append(offset + u"<%s>" % name)<br>
addDict(value, offset + u" " * 4)<br>
lines.append(offset + u"</%s>" % name)<br>
elif isinstance(value, list):<br>
for item in value:<br>
if isinstance(item, dict):<br>
addDict(item, offset + u" " * 4)<br>
else:<br>
lines.append(offset + u"<%s>%s</%s>" % (name, escape(unicodify(item)), name))<br>
else:<br>
if value != "":<br>
pass<br>
addDict(d, u"")<br>
lines.append(u"")<br>
return u"/n".join(lines)</p>
<h3>二、利用jsoncpp将json字符串转换为Vector</h3>
<p></p>
<p>在API测试过程中经常会遇到传入参数为复杂类型,一般情况下在python下,习惯用字典来表示复杂类型。但是c++对字符串的处理是比较弱智的,一般
c++里边会用vector来存储复杂类型,那么就存在转换的问题,下面小段代码记录了将字符串转换为Vector的过程</p>
<p>待转换的字符串如下:</p>
<p>const char * jsongroupinfo="[{/"groupId/" :946838524,/"groupname/" :/"bababa/", /"mask/":1,/"parentid/":946755072}]";</p>
<p>转换程序片段</p>
<p> Json::Reader reader;<br>
Json::Value json_object;<br>
if (!reader.parse(jsongroupinfo, json_object))<br>
return "parse jsonstr error";<br>
SUserChggroup sucg;<br>
VECTOR< SUserChggroup > m_groupInfo;<br>
for(int i = 0; i < json_object.size(); i ++)<br>
{<br>
Json::Value ¤t = json_object[i];<br>
sucg.m_groupId = current["groupId"].asInt();<br>
sucg.m_groupName = current["groupname"].asString();<br>
sucg.m_mask = current["mask"].asInt();<br>
sucg.m_parentId = current["parentid"].asInt();<br>
m_groupInfo.push_back(sucg);<br>
}</p>
<p></p>
<h3 class="title_txt">三、python中将json字符串转换为dict</h3>
<p>首先要确认是否存在simplejson的类库,python2.6及以上版本默认自带,</p>
<p>python2.5需要到如下目录下载</p>
<p>http://pypi.python.org/packages/source/s/simplejson/simplejson-2.1.2.tar.gz#md5=a856f9ae9ab3749991a93ddeafadc554</p>
<p>接下来的代码如下</p>
<p>import simplejson</p>
<p>js = "{/"description/":/"fdsafsa/",/"order/":/"1/",/"place/":/"22
Plainsman Rd, Mississauga, ON,
Canada/",/"lat/":43.5969175,/"lng/":-79.7248744,/"locationDate/":/"03/24/2010/"},{/"description/":/"sadfdsa/",/"order/":/"2/",/"place/":/"50
Dawnridge Trail, Brampton, ON,
Canada/",/"lat/":43.7304774,/"lng/":-79.8055435,/"locationDate/":/"03/26/2010/"},"</p>
<p>simplejson.loads('[%s]' % js[:-1])</p>
<p>三行代码搞定,为什么python代码总是那么简单呢</p>
<p></p>
<p></p>
<p>可见python在处理结构化数据方面的能力还是相当强悍的</p>
<p></p>
<h3>一.python 下xml和dict相互转化,含attributes</h3>
<p>我们写测试用例或者配置文件很多都是用xml文件来存储,但是数据要在程序中被使用,还是拿dict来用比较方便,所以有必要掌握xml转换为dict的技巧。互转程序片段如下:</p>
<p>from lxml import etree</p>
<p>def dictlist(node):<br>
res = {}<br>
res[node.tag] = []<br>
xmltodict(node,res[node.tag])<br>
reply = {}<br>
reply[node.tag] = {'value':res[node.tag],'attributes':node.attrib}<br><br>
return reply</p>
<p>def xmltodict(node,res):<br>
rep = {}<br><br>
if len(node):<br>
#n = 0<br>
for n in list(node):<br>
rep[node.tag] = []<br>
value = xmltodict(n,rep[node.tag])<br>
if len(n):<br><br>
value = {'value':rep[node.tag],'attributes':n.attrib}<br>
#print value<br>
res.append({n.tag:value})<br>
else :<br>
#print rep[node.tag][0]<br>
res.append(rep[node.tag][0])<br><br>
else:<br>
value = {}<br>
value = {'value':node.text,'attributes':node.attrib}<br>
#print value<br>
res.append({node.tag:value})<br><br>
return <br>
def fromstring(strdict=None):<br>
root = etree.fromstring(strdict)<br>
return dictlist(root)</p>
<p>def parse(filename=None):<br>
tree = etree.parse(filename)<br>
return dictlist(tree.getroot())</p>
<p>
def main():<br>
tree = etree.parse('test.xml')<br>
print tree<br>
res = dictlist(tree.getroot())<br>
print res<br><br>
def dict2xml(d):<br>
from xml.sax.saxutils import escape<br>
def unicodify(o):<br>
if o is None:<br>
return u'';<br>
return unicode(o)<br>
lines = ["<?xml version=/"1.0/" encoding=/"utf-8/"?>"]<br>
def addDict(node, offset):<br>
for name, value in node.iteritems():<br>
if name == "attributes":<br>
strqq = lines[len(lines)-1]<br>
index = strqq.find(u"<")<br>
strqq = strqq[index+1:len(strqq)-1]<br>
for x,y in value.iteritems():<br>
strqq = strqq + u" " *4 + u"%s='%s'"%(x,y)<br>
lines[len(lines)-1] = u" " * index + u"<%s>"%(strqq)<br>
else:<br>
if isinstance(value, dict):<br>
lines.append(offset + u"<%s>" % name)<br>
addDict(value, offset + u" " * 4)<br>
lines.append(offset + u"</%s>" % name)<br>
elif isinstance(value, list):<br>
for item in value:<br>
if isinstance(item, dict):<br>
addDict(item, offset + u" " * 4)<br>
else:<br>
lines.append(offset + u"<%s>%s</%s>" % (name, escape(unicodify(item)), name))<br>
else:<br>
if value != "":<br>
pass<br>
addDict(d, u"")<br>
lines.append(u"")<br>
return u"/n".join(lines)</p>
<h3>二、利用jsoncpp将json字符串转换为Vector</h3>
<p></p>
<p>在API测试过程中经常会遇到传入参数为复杂类型,一般情况下在python下,习惯用字典来表示复杂类型。但是c++对字符串的处理是比较弱智的,一般
c++里边会用vector来存储复杂类型,那么就存在转换的问题,下面小段代码记录了将字符串转换为Vector的过程</p>
<p>待转换的字符串如下:</p>
<p>const char * jsongroupinfo="[{/"groupId/" :946838524,/"groupname/" :/"bababa/", /"mask/":1,/"parentid/":946755072}]";</p>
<p>转换程序片段</p>
<p> Json::Reader reader;<br>
Json::Value json_object;<br>
if (!reader.parse(jsongroupinfo, json_object))<br>
return "parse jsonstr error";<br>
SUserChggroup sucg;<br>
VECTOR< SUserChggroup > m_groupInfo;<br>
for(int i = 0; i < json_object.size(); i ++)<br>
{<br>
Json::Value ¤t = json_object[i];<br>
sucg.m_groupId = current["groupId"].asInt();<br>
sucg.m_groupName = current["groupname"].asString();<br>
sucg.m_mask = current["mask"].asInt();<br>
sucg.m_parentId = current["parentid"].asInt();<br>
m_groupInfo.push_back(sucg);<br>
}</p>
<p></p>
<h3 class="title_txt">三、python中将json字符串转换为dict</h3>
<p>首先要确认是否存在simplejson的类库,python2.6及以上版本默认自带,</p>
<p>python2.5需要到如下目录下载</p>
<p>http://pypi.python.org/packages/source/s/simplejson/simplejson-2.1.2.tar.gz#md5=a856f9ae9ab3749991a93ddeafadc554</p>
<p>接下来的代码如下</p>
<p>import simplejson</p>
<p>js = "{/"description/":/"fdsafsa/",/"order/":/"1/",/"place/":/"22
Plainsman Rd, Mississauga, ON,
Canada/",/"lat/":43.5969175,/"lng/":-79.7248744,/"locationDate/":/"03/24/2010/"},{/"description/":/"sadfdsa/",/"order/":/"2/",/"place/":/"50
Dawnridge Trail, Brampton, ON,
Canada/",/"lat/":43.7304774,/"lng/":-79.8055435,/"locationDate/":/"03/26/2010/"},"</p>
<p>simplejson.loads('[%s]' % js[:-1])</p>
<p>三行代码搞定,为什么python代码总是那么简单呢</p>
<p></p>
<p></p>
<p>可见python在处理结构化数据方面的能力还是相当强悍的</p>
<p></p>