Convert XML to JSON with pebble.js - javascript

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!

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
});

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.

Related

How do I HTTP GET a .js file and extract 'exports' variables?

I am writing a site in Laravel to complement a game written in Node. It pulls information directly from the game's .js files stored on GitHub and the plan is to use Vue to generate some nice HTML to display the data.
The .js files are of the form:
'use strict'
let x = {...};
exports.x = x;
I can import the files using a PHP request (simply using 'file') and pass them to JS with either jQuery.getScript or axios.get (so far). However, I am having real trouble coming up with a way to extract the 'x' values here under exports. If I were writing a JS app in node, I would simply do the following:
var xFile = require('xFile');
var x = xFile.x;
However, I can't figure out how to do that here as both GET methods return a string, not a JS file. JSON.parse() doesn't work, and I would like to come up with a solution that doesn't just replace the non-JSON text as I would need a reusable solution for other files. I don't suppose anybody has any ideas?
Thanks so much!
You could try something like below.
you could create the script tag dynamically and attach the script in the body and add your javascript code using innerHTML.
You call this script in your ajax response code.
let script = document.createElement('script');
script.innerHTML = 'alert("Hi")';
document.querySelector('body').appendChild(script);
I managed to figure it out! It's a little janky, but you can run a node file in PHP with the exec command. I just wrote a node file to import the file and return the useful data. This probably isn't an optimal solution, but it works for me since I'm much more confident with JS than with PHP.

Pushing to an array in a separate JSON file

Lets say I have a JSON file, with an array inside of that JSON file.
{
"users": ["288381238123", "12312123123"]
}
Now I want to push to that array, and I have that file required at the top
const userList = require('../rolecall.json');
Then I have some other code here, which is seemingly supposed to push to that array
const users = userList.users;
users.push('82313123');
Now when I check back to the JSON file, there is no addition to the array. Why is that? If anyone could help me, that would be great.
When you 'push' to the array in Javascript, you are only changing the Javascript object.
Edit: taking Lyon's comment into account
The short answer is, you can't change a file on the client machine using javascript. That would be a huge security issue (though it used to be possible, fun times).
However, you can ask the browser to display a save dialog asking the user whether they want to save the content of your json to a file.
Old answer
If you want to save the changes to a file located on the server, you need to send the informations to said server, preferably via a POST request.
A simple way to do it is to use Ajax requests.
You can use the JSON.stringify method to format your users object.
xhttp.send(JSON.stringify(users));
Then you can handle the request on the server. The way to do that depends on the language used (PHP, Ruby, Node, etc)
Observations :
You are pushing a element into a local array userList. If you want to update the rolecall.json file, you'll need to write back to that file.
Javascript (client side) has not functionality to create, edit etc.. files.You can do it in back-end side.
Workaround :
You got your json in userList constant variable. now you can push that element into the array and then write back to rolecall.json if you're manipulating it in your backend (ie.: NodeJs)
const userList = {
"users": ["288381238123", "12312123123"]
};
userList.users.push('82313123');
console.log(userList);
In node.js you can use the fs library.
fs = require('fs');
fs.writeFile('fileName.json', JSON.stringify(userList));

extract the value of an array in an existing javascript file

I'm trying to convert values defined in a javascript file to a json file or extract those values to some other format that I can process with python. Does anyone know of a python library, node.js package or other method for doing this with a local file? I cannot use ajax or php for this task.
Context:
I have a javascript file called file.js, in which there are no functions, but a number of lengthy arrays defined in the following fashion:
var an_array1 = new Array();
an_array[1] = {some array values 1}
...
an_array[n] = {some array values n}
var another_array = new Array();
another_array[1] = {some other array values 1}
...
another_array[m] = {some other array values m}
No functions are included in this file, just the calls to var and the subsequent setting of the array values.
Similar questions provide answers that focus around using ajax or php, but I do not think I can use these tools for this purpose. I can, however, use node.js, python and any associated libraries/packages. I would also be game to try an awk/sed type script, but I don't think this will work here, since the data I want requires file.js to be parsed/processed first.
Ideal outcome
Ultimately, I'd like to use some method to process the file.js, extract the value of one particular array to its own file as JSON, or some other, similar format (XML would be fine too, even csv would work). e.g.:
file.json:
[{some array values 1},...,{some array values n}]
Does anyone know how this might be done? There are some questions similar to this, but those assume that I am querying a website or something, which is not the case here.
Here's a node file that could do this for you if the file.js file is structured to declare the desired variables at the top level. If that isn't the case, you will have to show us what exactly file.js looks like.
// load filesystem module
var fs = require("fs");
// read JS file and execute it
var data = fs.readFileSync("file.js", {encoding: "utf8"});
eval(data);
// write data out to files
fs.writeFile("result1.json", JSON.stringify(an_array1));
fs.writeFile("result2.json", JSON.stringify(an_array2));
You would then just run this JS file with node.js.
This would use the V8 JS interpreter in node to parse the JS file with your variables in it. It would then load the file system module and then write the JSON representation of two separate arrays out to files.
You can then write Python to read those files, parse the JSON into a form Python understands (Python has JSON parsing built-in) and then do whatever you want with the data in Python.

Can you read line by line in javascript?

Is there any way to read a file line by line in javascript, specifically this file which is a dictionary. I was trying to build a replica of a java anagram solver I made a few months ago, but hit this problem of not being able to read a file line by line. I could download the file and store it locally if that would make any difference to being able to read it.
Use YQL:
http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22http%3A%2F%2Fdocs.oracle.com%2Fjavase%2Ftutorial%2Fcollections%2Finterfaces%2Fexamples%2Fdictionary.txt%22&format=json&diagnostics=true&callback=cbfunc
Here's what the fiddle looks like:
window.callback = function(a) { window.file = a.query.results.body.p; go(); };
$.getScript('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22http%3A%2F%2Fdocs.oracle.com%2Fjavase%2Ftutorial%2Fcollections%2Finterfaces%2Fexamples%2Fdictionary.txt%22&format=json&diagnostics=true&callback=callback');
window.go = function() {
var terms = file.split(' ');
for (var i = 0; i < 100; i++)
console.log(terms[i])
};
The fiddle only does the first 100 but you get the idea (I hope).
In most circumstances, you could just read the file into memory and then parse it into lines. If you read the whole thing into memory with an ajax call, you could just use data.split("\n") to convert it to an array of lines.
You should initiate Ajax Request for such Operation. Reading a file line by line although is not recommended via Ajax, as you will end up create loads of server requests in the process;as JavaScript is all about Client side and limited access also. Ajax request to server is recent years add-on to it.
Definitely you are searching some information using some keywords; so it would be wise if you add the search logic on server functions; call the specific function via Ajax and return back result-set to the browser. That function could be a file that generates result or, a web service. You choose your flavor.
Alternate option would be to re-code the file information to JSON (about JSON) at start and let it roll to client js script. I would not recommend XML for this as its gonna eatup loads of browser memory in the processing terms. Been there! :(. Since JavaScript has native support to JSON, it will go smooth. Warning this exposes data to local.

loading and parsing a file with JS

I want to load an external file using AJAX GET and then parse it for the relevant information on it leaving out all the comments.
file: stuff.conf
: This is the list
: of colors needed
#5d3939 : nice
#9e1818 : ugly!
#cd7979
#409c81
#6e6f14 : ok...
I want the hex colours in an array.
Please help!
Here you go:
var arr = response.match(/\#[a-f0-9]{6}/gi);
where response is your Ajax response string.
Live demo: http://jsfiddle.net/simevidas/RnPS3/1/
You can write your own JS to parse any type of data format. But, the somewhat standard way to interchange data like this with the least hassle is to put the data in the JSON format with the color values in an array (or whatever format you want them to end up on). You then read the contents of the file into a string variable and then call a JSON parser. The return value of the parser will be an array of color values (if that's how you format the JSON). The latest browsers have JSON parsers built in. For cross-browser compatibility with older browsers, you can either use a parser in one of the common libraries like jQuery or YUI or find code on the web to add just a JSON parser.

Categories