python json转xml
时间: 2023-06-03 11:04:06 浏览: 201
可以使用第三方库如xmltodict来实现。具体代码可以参考如下:
import json
import xmltodict
json_str = '{"name": "John", "age": 30}'
json_data = json.loads(json_str)
xml_data = xmltodict.unparse({"person": json_data})
print(xml_data)
相关问题
python json转xml格式
你可以使用 Python 的 `xml.etree.ElementTree` 模块来将 JSON 格式转换为 XML 格式。具体步骤如下:
1. 首先,将 JSON 格式转换为 Python 的字典或列表对象。可以使用 `json.loads()` 函数来实现。
```python
import json
json_str = '{"name": "Alice", "age": 20, "hobbies": ["reading", "traveling"]}'
data = json.loads(json_str)
```
2. 然后,使用 `xml.etree.ElementTree` 模块创建根元素,并递归地将字典或列表转换为 XML 元素。
```python
import xml.etree.ElementTree as ET
def json_to_xml(data):
root = ET.Element("root")
if isinstance(data, dict):
for key, value in data.items():
child = ET.Element(key)
root.append(child)
json_to_xml(value, child)
elif isinstance(data, list):
for item in data:
child = ET.Element("item")
root.append(child)
json_to_xml(item, child)
else:
root.text = str(data)
return root
```
3. 最后,使用 `ET.tostring()` 函数将根元素转换为 XML 字符串。
```python
xml_str = ET.tostring(json_to_xml(data))
print(xml_str)
```
完整代码如下:
```python
import json
import xml.etree.ElementTree as ET
def json_to_xml(data):
root = ET.Element("root")
if isinstance(data, dict):
for key, value in data.items():
child = ET.Element(key)
root.append(child)
json_to_xml(value, child)
elif isinstance(data, list):
for item in data:
child = ET.Element("item")
root.append(child)
json_to_xml(item, child)
else:
root.text = str(data)
return root
json_str = '{"name": "Alice", "age": 20, "hobbies": ["reading", "traveling"]}'
data = json.loads(json_str)
xml_str = ET.tostring(json_to_xml(data))
print(xml_str)
```
Python xml转json
可以使用 Python 内置的 `xml.etree.ElementTree` 模块和 `json` 模块来实现 xml 转换为 json。
下面是一个简单的示例代码:
``` python
import xml.etree.ElementTree as ET
import json
# 读取 xml 文件
tree = ET.parse('sample.xml')
root = tree.getroot()
# 将 xml 转换为字典
xml_dict = {}
for child in root:
xml_dict[child.tag] = child.text
# 将字典转换为 json
json_data = json.dumps(xml_dict)
print(json_data)
```
这个示例代码假设 xml 文件的结构类似于:
``` xml
<root>
<name>John</name>
<age>30</age>
<gender>Male</gender>
</root>
```
如果 xml 文件的结构更加复杂,那么需要针对具体的情况做出相应的修改。
阅读全文
相关推荐
















