0

I am consuming XML in express server parsing it with express-xml-bodyparser, but the resulting object is basically unusable.

XML

<SubClass code="A07.0"/>
<SubClass code="A07.1"/>
<SubClass code="A07.2"/>
<SubClass code="A07.3"/>
<SubClass code="A07.8"/>
<SubClass code="A07.9"/>

is serialized as JSON

subclass:
[ { '$': { code: 'A07.0' } },
  { '$': { code: 'A07.1' } },
  { '$': { code: 'A07.2' } },
  { '$': { code: 'A07.3' } },
  { '$': { code: 'A07.8' } },
  { '$': { code: 'A07.9' } } ]

Is there way to pase it directly into

subclass: ['A07.0','A07.1','A07.2','A07.3','A07.8','A07.9']

or some easy way how to convert it into this array?

2
  • 1
    Array.from(parentNode.childNodes).filter(n => n.nodeType === 1).map(n => n.getAttribute('code')) Commented Jan 18, 2018 at 12:41
  • Under what logic would a serializer know to do what you're describing? What if the XML looked like this, what should it do then: <SubClass code="A07.0"/> <SubClass code="A07.1"/> <SubClass code="A07.2" subCode="5"/> <Field id="9" /> <SubClass code="A07.3"/> <SubClass code="A07.8"/> <SubClass code="A07.9"/> Commented Jan 18, 2018 at 12:46

2 Answers 2

1

You can set mergeAttrs option to true in order to remove $ properties:

 xmlparser({ mergeAttrs: true, explicitArray: false})

Output:

SubClass: [
    { code: "A07.0" },
    { code: "A07.1" },
    { code: "A07.2" },
    { code: "A07.3" },
    { code: "A07.8" },
    { code: "A07.9" }
]

Or you can just use array.map() method:

var data = { subclass:
[ { '$': { code: 'A07.0' } },
  { '$': { code: 'A07.1' } },
  { '$': { code: 'A07.2' } },
  { '$': { code: 'A07.3' } },
  { '$': { code: 'A07.8' } },
  { '$': { code: 'A07.9' } } ] };
  
  
var result = data.subclass.map( (obj) => {
    return obj.$.code;
});

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

0

If you want to convert json into an object then maybe something like...

var arr = Object.keys(json).map(function(x) { return obj[x] });

With jQuery

var arr = $.map(json, function(x) { return x});

1 Comment

This wouldn't work on the "JSON" that OP posted, and I think OP is looking to skip intermediate JSON step.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.