Convert XML to JavaScript Object - javascript

I have an XML file with the following content:
<directory>
<app>
<title>Carrot</title>
<url>www.carrot.com</url>
</app>
<app>
<title>Cucumber</title>
<url>www.cucumber.com</url>
</app>
</directory>
Assuming I had been able to read it and store the content as a string:
s = '<directory><app><title>Carrot</title><url>www.google.com</url></app><app><title>Cucumber</title><url>www.cucumber.com</url></app></directory>';
How do I convert it to a JavaScript object like the following?
{
"directory": {
"app": [
{ "title": "Carrot", "url": "www.carrot.com" },
{ "title": "Cucumber", "url": "www.cucumber.com" }
]
}
}

I use this plugin ... http://www.thomasfrank.se/xml_to_json.html
Its always worked a charm for me.

I think you are looking for the answer to the following question Convert XML to JSON (and back) using Javascript
XML <-> JSON conversion in Javascript
quoted answer
I think this is the best one: Converting between XML and JSON
Be sure to read the accompanying article on the Xml.com O'Reilly site (linked to at the >bottom). The writer goes into details of the problems with these conversions, which I think >you will find enlightening. The fact that O'Reilly is hosting the article should indicate >that Stefan's solution has merit.

Related

How would I go about embedding JSON data into my HTML file?

I'm currently working on a project where I'm creating a playable ad I'd like to upload to Facebook.
According to Facebook's ad specifications: (https://www.facebook.com/business/help/412951382532338?helpref=faq_content)
They only accept a single HTML file of size less than 2mb for uploading. This means I need to inline all external references to a single HTML file. Which brings me to my problem:
In order to speed up development I use game engines like PlayCanvas and Phaser Editor. The issue I'm facing with most game engines is that they always have data stored in a JSON file that makes it difficult to reference into an HTML file. Is there any way I can inline this data into my file as well?
JSON data containing a base64 encoded image:
"section": [{
"type": "image",
"key": "logo",
"url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEn.........",
"overwrite": false
}],
"meta": {
"generated": "1543491968969",
"app": "Phaser Editor",
"url": "http://phasereditor.boniatillo.com",
"version": "1.0",
"copyright": "Arian Fornaris (c) 2015,2016"
}
}
Function that references this data in my HTML file:
Level.prototype.preload = function ()
{
this.load.pack('section', 'assets/pack.json');
};
Is there a way I can load the referenced data from the JSON file into this function? I've tried using
<script id="data" type="application/json">
{
JSON data here
}
</script>
and then inlining code inside the braces. Replacing 'assets/pack.json' with this code. I've also tried replacing 'section' with it's respective JSON data but I've not been successful. I hope there's someone out there who can understand how this function works and how it would be possible to inline this data there.
I'm also curious if there are any game engines or softwares that would output a single HTML file that I could use in my development.
I'd like to thank everyone in advance and I appreciate any help in solving this.
I think you can achieve this by creating a HTML field which is hidden and setting it's data- to be an object like this.
<div data-foobar='{"foo":"bar"}'></div>
Check out this link :
http://jsfiddle.net/GlauberRocha/Q6kKU/

Accessing information from an HTTPS JSON file

I want to use information from what I believe is a JSON file, using JavaScript or some derivation of it. This is the file:
https://mylularoe.com/llrapi/v3/get-inventory/
The file looks (snippet) like this:
{
"3 Day Shipping - ANY": {
"model": "3 Day Shipping - ANY",
...
"quantities": {
"": {
"count": "52710",
...
}
}
}
}
I want to read the file and make an alert pop up with the count (in this case, 52710).
I think I'm to use JQuery, by adding:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
to the header.
By my investigation, I should be able to use JSON.parse(data) if I could access the string, but I can't seem to get that going.
I'm working with an HTML file on my local computer, but I don't believe that is relevant.
I will update the question with more information as required. Thank you for your help. I've used Stack Overflow a million times and this is my first attempt at asking a question.

Parse JSON file in Middleman data folder to Javascript File as an Array

Sorry if this comes off super basic and I'm a Middleman newb, but I'm trying to take the JSON file in my data folder, parse the data in a Javascript file (I'm using jQuery), and then use it for SoundManager2.
I've done my research around the internet looking for answers, and here's where I've got:
My JSON file within the data folder for Middleman
{
"sound": [
{
"name": "Holidead",
"url": "https://dl.dropboxusercontent.com/u/80054631/music/Holidead.mp3"
},
{
"name": "Where Did It All Go",
"url": "https://dl.dropboxusercontent.com/u/80054631/music/Where%20Did%20It%20All%20Go_1.mp3"
},
{
"name": "When We Ride",
"url": "https://dl.dropboxusercontent.com/u/80054631/music/When%20We%20Ride.mp3"
}
]
}
Then in config.rb, I've tried doing this at the bottom of the file:
string = File.read('data/soundlist.json')
json = JSON.parse(string)
So my question is how do I connect the parsing in the config.rb with the Javascript file to read the JSON file in jquery Ajax? I want to turn the data into an array and use the URLs to play sounds with SoundManager2. I believe I'm missing a few steps between the Ruby file and the JS file.
I believe I'm missing a few steps between the Ruby file and the JS file.
Exactly! You can have file-name.js.erb files which will be processed by middleman as .html.erb files are processed. ie, anything in
<%= %>
will be evaluated
Put this in config.rb
string = File.read('data/soundlist.json')
config[:json] = JSON.parse(string)
have file name have extention .js.erb. say json-data.js.erb
var json_data = <%= config[:json] %>;
console.log('json_data');
now build the project using
middleman build
If you check build/json-data.js, you can see the variable json_data has the json value.

Error parsing JSON which starts with "var ..."

I got into a little thing while getting a JSON file from a server, the JSON file contains something like this:
var reviews = [
{
"firstName":"Simon",
"lastName":"Lock",
"fullName":"Simon Lock",
"location":"San Francisco",
"reviewTitle":"Super quality.. I will show here again!",
"reviewBody":"Super nice quality, fast devilery, good prices. I will shop here again!",
"starRating":"5"
},
{
"firstName":"John",
"lastName":"Smith",
"fullName":"John Smith",
"location":"New York",
"reviewTitle":"Princely Sum",
"reviewBody":"A decent local curry house in Faversham, Kent known for its Elvis nights.",
"starRating":"4"
},
];
And as expected, I get an error while getting the file with $.ajax:
SyntaxError: Unexpected token v
Since is not a valid JSON format, but I did also try to do it with another kind of dataType.
My question is:
Is there any way to get that variable in JSON file stored in another variable so it can be manipulated normally?
also I did try to use FileReader() but I didn't work for me.
thanks
JSON is just a way of storing data, not JavaScript code. it doesn't know what to do with var reviews =. All you store in your JSON file is the data, like below.
[
{
"firstName":"Simon",
"lastName":"Lock",
"fullName":"Simon Lock",
"location":"San Francisco",
"reviewTitle":"Super quality.. I will show here again!",
"reviewBody":"Super nice quality, fast devilery, good prices. I will shop here again!",
"starRating":"5"
},
{
"firstName":"John",
"lastName":"Smith",
"fullName":"John Smith",
"location":"New York",
"reviewTitle":"Princely Sum",
"reviewBody":"A decent local curry house in Faversham, Kent known for its Elvis nights.",
"starRating":"4"
}
]
Bear in mind that this is not something I recommend in cases where security is critical, but you do have the option of using the eval() function on the plain text of the file.
eval('var reviews = [
{
"firstName":"Simon",
"lastName":"Lock",
"fullName":"Simon Lock",
"location":"San Francisco", ...
would give you a variable reviews that contains the object you want.
edit: yes eval is evil, I know

JSON Response from web service - best practices question

I'm writing a simple web service that return a JSON response. It'll be heavily used, so I want to try and make the JSON response as small as possible for performance reasons. I'm on the fence over a design decision; penny for your thoughts!
My JSON response from the server looks like this:
{
"customers":
[
{
"id": "337",
"key": "APIfe45904c"
},
{
"id": "338",
"key": "somethingDifferent"
},
{
"id": "339",
"key": "APIfe45904c"
},
{
"id": "340",
"key": "APIfe45904c"
}
]
}
The APIfe45904c here is used in about 60-70% of the records, so I could also modify the the JSON response to remove the repeated information and add a default_key i.e. if there's no key specified, the client should assume the default_key like this:
{
"default_key": "APIfe45904c",
"customers":
[
{
"id": "337"
},
{
"id": "338",
"key": "somethingDifferent"
},
{
"id": "339"
},
{
"id": "340"
}
]
}
No client is using the web service yet, so this wouldn't break anything. Is this good practice? It works, and makes for a small JSON response, but I'm conflicted. I like the KISS principle for developers using the service, but I also want as small a JSON response as possible.
I was tempted to replace customers with c, id with i and key with k to aid reducing the file size, but I figured this will be a problem if I want to get other clients to start using it. Should I drop the idea of default_key for the same reason?
Each JSON response will likely be no more 200 lines of id/key pairs, so I don't need to incorporate pagination, etc.
I would keep it simple as you say, and then use gzip to compress it. It should compress very well as it is repetitive, and remains convenient for programmers.
See here for pointers in outputting gzip headers for AJAX: Is gzip encoding compatible with JSON?
Unless you have very special performance needs, I would always choose clarity over brevity. Especially for an API that is going to be used by many developers.
You should use the consistent format where each record has an id and a key field. What you lose in bandwidth you gain from not having to pre-process the JSON on the client-side.
I tend to analyze my JSON data structure like you but in the end it isn't worth the tiny bit of space you save. Your JSON data structure looks good... have you seen Twitter's JSON data structure? Now that is ugly.
I would go with the default key idea, but I wouldn't go as far as shortening the attribute names since that can be confusing. Perhaps you can take an argument from the web service call (from query string) that specifies whether or not the client desires to have shortened attribute names.

Categories