soldair / node-jsontoxml

this renders a simple javascript object structure into xml/html. js objects are easier to modify than strings so no need to parse a whole dom to reliably add a few elements. while this could support async callbacks it doesn't. if people need it i will be happy to add support.
MIT License
101 stars 38 forks source link

Handling array items #31

Open jlguenego opened 6 years ago

jlguenego commented 6 years ago

I need to convert the following json into xml:

{
    "content": [
        {
            "_id": "012345678901234567890123",
            "lastname": "Guénégo",
            "firstname": "Jean-Louis"
        },
        {
            "_id": "5ae5ef542523d439d8083335",
            "lastname": "Phengsiaroun",
            "firstname": "Dany",
            "__v": 0
        }
    ]
}

The output does not satisfy because it does not clearly sepearate the array items:

<content>
    <_id>012345678901234567890123</_id>
    <lastname>Guénégo</lastname>
    <firstname>Jean-Louis</firstname>
    <_id>5ae5ef542523d439d8083335</_id>
    <lastname>Phengsiaroun</lastname>
    <firstname>Dany</firstname>
    <__v>0</__v>
</content>

I would suggest to add in the options something like: handleArrayElement: true

that would produce:

<content>
    <item>
        <_id>012345678901234567890123</_id>
        <lastname>Guénégo</lastname>
        <firstname>Jean-Louis</firstname>
    </item>
    <item>
        <_id>5ae5ef542523d439d8083335</_id>
        <lastname>Phengsiaroun</lastname>
        <firstname>Dany</firstname>
        <__v>0</__v>
    <item>
</content>
jlguenego commented 6 years ago

In fact it is a nice to have because I can quickly solve it outside of the jsontoxml lib.

function handleArray(js) {
    if (js instanceof Array) {
        return js.map(n => ({item: n}));
    }
    if (js instanceof Object) {
        const result = {};
        for (let p in js) {
            result[p] = handleArray(js[p]);
        }
        return result;
    }
    return js;
}
MahmoudYaser1 commented 5 years ago

in my case i want to embed array items without array key .. for example this is before

<content>
    <item>
        <lastname>Guénégo</lastname>
        <firstname>Jean-Louis</firstname>
    </item>
    <item>
        <lastname>Phengsiaroun</lastname>
        <firstname>Dany</firstname>
    <item>
</content>

just without the array key

<item>
        <lastname>Guénégo</lastname>
        <firstname>Jean-Louis</firstname>
    </item>
    <item>
        <lastname>Phengsiaroun</lastname>
        <firstname>Dany</firstname>
<item>
ConPac commented 5 years ago

Hi @jlguenego:

Just run into this issue today, until I realized from the example in readme that all that's needed is a new object with name and children properties:

let jsonObject = JSON.parse('{"content": [ ... ]}')
let arrayObject = {}
arrayObject.content = jsonObject.content.map(o => Object.assign({name: 'item', children: o})
jsontoxml(arrayObject)