我的xml源文件如下所示
我的schema是
{
"type": "record",
"name": "main",
"namespace": "list1",
"fields": [
{
"name": "a",
"type": "string"
},
{
"name": "b",
"type": "string"
},
{
"name": "c",
"type": {
"type": "record",
"name": "main",
"namespace": "c.list1",
"fields": [
{
"name":"list2",
"type": {
"type": "array",
"items": {
"type": "record",
"name": "main",
"namespace": "list2.c.customer",
"fields": [
{
"name": "d",
"type": "string"
},
{
"name": "e",
"type": "string"
}
]
}
}
}
]
}
}
]
}
转换出来的json格式如下
{"a":"china","b":"hb","c":{lists:[{"d":2222,"e":"s130"},{"d":2222,"e":"s130"}]}}现在想让转换出来的json没有c这个层级,就是{"a":"china","b":"hb",lists:[{"d":2222,"e":"s130"},{"d":2222,"e":"s130"}]}
那么我的schema应该改成什么样的?
源于ChatGPT 仅供参考
根据您提供的信息,假设您使用以下代码将 XML 转换为 JSON:
```javascript
const xml = `<?xml version="1.0" encoding="UTF-8"?>
<main>
<a>value_a</a>
<b>value_b</b>
<c>
<list2>
<customer>
<d>value_d1</d>
<e>value_e1</e>
</customer>
<customer>
<d>value_d2</d>
<e>value_e2</e>
</customer>
</list2>
</c>
</main>`;
const schema = {
"type": "record",
"name": "main",
"namespace": "list1",
"fields": [
{
"name": "a",
"type": "string"
},
{
"name": "b",
"type": "string"
},
{
"name": "c",
"type": {
"type": "record",
"name": "main",
"namespace": "c.list1",
"fields": [
{
"name":"list2",
"type": {
"type": "array",
"items": {
"type": "record",
"name": "main",
"namespace": "list2.c.customer",
"fields": [
{
"name": "d",
"type": "string"
},
{
"name": "e",
"type": "string"
}
]
}
}
}
]
}
}
]
};
const avro = require('avsc');
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xml, "text/xml");
const result = avro.parse(schema).fromBuffer(Buffer.from(JSON.stringify(xmlDoc)));
console.log(result);
当您运行以上代码时,JSON 对象中数组 list2
外面会多包一层。这是因为 AvroSchema 库默认使用对象作为根节点处理 JSON 树,而 XML 树中根元素只有一个,因此将其转换为对象后会多出一层包装。
要解决这个问题,可以在定义 schema 时使用 wrapSingle
属性将根节点指定为数组类型。例如:
const schema = {
"type": "array",
"items": {
"type": "record",
"name": "main",
"namespace": "list1",
"fields": [
{
"name": "a",
"type": "string"
},
{
"name": "b",
"type": "string"
},
{
"name": "c",
"type": {
"type": "record",
"name": "main",
"namespace": "c.list1",
"fields": [
{
"name":"list2",
"type": {
"type": "array",
"items": {
"type": "record",
"name": "main",
"namespace": "list2.c.customer",
"fields": [
{
"name": "d",
"type": "string"
},
{
"name": "e",
"type": "string"
}
]
}
}
}
]
}
}
]
},
"wrapSingle": true
};
这样,当您运行上述修改后的代码时,将不会再出现多余的包装层。
```