NaturalIntelligence / fast-xml-parser

Validate XML, Parse XML and Build XML rapidly without C/C++ based libraries and no callback.
https://naturalintelligence.github.io/fast-xml-parser/
MIT License
2.45k stars 296 forks source link

Why it has "Object" rather than some value? #599

Closed Mnemosynel closed 1 year ago

Mnemosynel commented 1 year ago

Description

### Input ```ts const data = ` Item 1 10.99 Item 2 19.99 `; ``` ### Code ```ts function parseOriginFragmentDetail(data: string): any { const options = { ignoreAttributes: true, ignoreNameSpace: true, parseAttributeValue: false, parseNodeValue: true, allowBooleanAttributes: true }; const parser = new XMLParser(options); const jsonObj = parser.parse(data); return jsonObj; } let jsonData1 = parseOriginFragmentDetail(data); console.log(jsonData1); console.log("***************"); ``` ### Output

{ items: { item: [ [Object], [Object] ] } }


expected data

 {
    "items": {
        "item": [
            {
                "name": "Item 1",
                "price": 10.99
            },
            {
                "name": "Item 2",
                "price": 19.99
            }
        ]
    }
}

Would you like to work on this issue?

Bookmark this repository for further updates. Visit SoloThought to know about recent features.

github-actions[bot] commented 1 year ago

We're glad you find this project helpful. We'll try to address this issue ASAP. You can vist https://solothought.com to know recent features. Don't forget to star this repo.

cecia234 commented 1 year ago

Hi! I think that's how console.log() works when printing an array of objects, when the array itself is contained in a nested object. For example, if you try to print a similar object with this script:

const aaa = {
    a:{
        b: [ { d: 1 }, { e: 3 } ]
    }
}
console.log(aaa);

You obtain

{ a: { b: [ [Object], [Object] ] } }

If you need the object parsed as string you can use JSON.stringify(). With your script it should look something like this:

const data = `
<items>
  <item>
    <name>Item 1</name>
    <price>10.99</price>
  </item>
  <item>
    <name>Item 2</name>
    <price>19.99</price>
  </item>
</items>
`;

function parseOriginFragmentDetail(data: string): any {
  const options = {
    ignoreAttributes: true,
    ignoreNameSpace: true,
    parseAttributeValue: false,
    parseNodeValue: true,
    allowBooleanAttributes: true
  };

  const parser = new XMLParser(options);
  const jsonObj = parser.parse(data);

  return jsonObj;
}
let jsonData1 = parseOriginFragmentDetail(data);
console.log(JSON.stringify(jsonData1));
console.log("***************");

You should see this in the console

{"items":{"item":[{"name":"Item 1","price":10.99},{"name":"Item 2","price":19.99}]}}
***************
Mnemosynel commented 1 year ago

It works! Thanks!