Convert XML to JSON with pebble.js

758 views Asked by At

I am writing a small application for my Pebble. The intent is to send web services to a server and then process the XML response. The problem here is that Pebble.JS does not support XML responses, only text or JSON responses. I am looking for a way to convert the response to JSON to easily make use of the information. I cannot find a working way for Pebble.JS to accomplish this.

Does anyone know how to get the attributes and the child elements (with its attributes) of the XML in JSON in Pebble.JS?

Thanks!

2

There are 2 answers

1
i__Mrvin On

You could use a Node XML Parser like this one (https://github.com/Leonidas-from-XIV/node-xml2js) and make it compatible to a "browser" with Browserify (https://github.com/substack/node-browserify).

Browserify usage: browserify raw-app.js -o compiled-app.js

I think you need to have nodejs installed too but this isn´t a big problem.

Here some code which written on-the-fly:

   var xml2js = require('xml2js');

   var xml = "<root>This is a root object!<child>This a child</child></root>"

   xml2js.parseString(xml, function (error, result) {
       console.log(result); // JSObject
   });
0
Kenneth Salomon On

The issue is that jQuery Mobile does not support responses coming in as XML. I have quite annoyingly run into this issue before. The way I got around it was by creating my own JSON Object with the expected response tags in the following way:

var IDs = message.match(/<id>(.*?)<\/id>/g);
var tempID = IDs[0].replace('<id>','').replace('</id>','');

That's just a part from my actual project that I was working on this for. It will require a little bit of modifying as per your needs to get it to how you want it. You likely will want to have that second line inside a loop with some other arrays from your .match() calls, when making your JSON Object. At the end, you need to use the JSON.parse(...); function call to assign a variable the JSON addressable object you've made.