Leonidas-from-XIV / node-xml2js

XML to JavaScript object converter.
MIT License
4.88k stars 602 forks source link

Cannot round-trip encoding/decoding #391

Open adamvoss opened 7 years ago

adamvoss commented 7 years ago

Given the following object as x:

[
    {
        "id": 2,
        "name": "An ice sculpture",
        "price": 12.5,
        "tags": [
            "cold",
            "ice"
        ],
        "dimensions": {
            "length": 7,
            "width": 12,
            "height": 9.5
        },
        "warehouseLocation": {
            "latitude": -78.75,
            "longitude": 20.4
        }
    },
    {
        "id": 3,
        "name": "A blue mouse",
        "price": 25.5,
        "dimensions": {
            "length": 3.1,
            "width": 1,
            "height": 1
        },
        "warehouseLocation": {
            "latitude": 54.4,
            "longitude": -32.7
        }
    }
]

The following fails (prints an error):

builder = new xml2js.Builder()
xml2js.parseString(builder.buildObject(x), function(err, res) { console.log(err) })

with the following error:

Error: Unencoded <
Line: 2
Column: 4
Char: 0
    at error (/home/vossad01/dev/any-json/node_modules/sax/lib/sax.js:651:10)
    at strictFail (/home/vossad01/dev/any-json/node_modules/sax/lib/sax.js:677:7)
    at SAXParser.write (/home/vossad01/dev/any-json/node_modules/sax/lib/sax.js:1080:13)
    at Parser.exports.Parser.Parser.parseString (/home/vossad01/dev/any-json/node_modules/xml2js/lib/xml2js.js:508:31)
    at Parser.parseString (/home/vossad01/dev/any-json/node_modules/xml2js/lib/xml2js.js:7:59)
    at Object.exports.parseString (/home/vossad01/dev/any-json/node_modules/xml2js/lib/xml2js.js:540:19)
    at repl:1:8
    at ContextifyScript.Script.runInThisContext (vm.js:23:33)
    at REPLServer.defaultEval (repl.js:339:29)
    at bound (domain.js:280:14)

Using 0.4.17 from npm

jcsahnwaldt commented 6 years ago

The main problem is that x is an array, not an object. The input to buildObject should be an object with one named property whose value is not an array. Otherwise, the results are more or less undefined.

@adamvoss, if you still have this issue, please let us know what you want to do (e.g. by posting a short XML sample etc.) and we can help you find a way.