Utilize this JavaScript tool to effortlessly transform an XML string into JSON format

Looking for the optimal javascript function, plugin, or library to effectively transform an XML string into JSON format.

One tool I came across is , but unfortunately, it struggles with strings that begin with 0. For example, 005321 may end up converted to 2769, which is not ideal.

So my question remains, what is the most reliable tool in javascript for converting XML to JSON?

EDIT: Has anyone found a solution that works seamlessly for this process?

Answer №1

I have found success with the following function:

convertXmlToJson = function(xmlData) {
    var jsonObj = {};
    if (xmlData.nodeType == 1) {                
        if (xmlData.attributes.length > 0) {
            jsonObj["@attributes"] = {};
            for (var k = 0; k < xmlData.attributes.length; k++) {
                var attr = xmlData.attributes.item(k);
                jsonObj["@attributes"][attr.nodeName] = attr.nodeValue;
            }
        }
    } else if (xmlData.nodeType == 3) { 
        jsonObj = xmlData.nodeValue;
    }            
    if (xmlData.hasChildNodes()) {
        for (var j = 0; j < xmlData.childNodes.length; j++) {
            var child = xmlData.childNodes.item(j);
            var nodeName = child.nodeName;
            if (typeof (jsonObj[nodeName]) == "undefined") {
                jsonObj[nodeName] = convertXmlToJson(child);
            } else {
                if (typeof (jsonObj[nodeName].push) == "undefined") {
                    var prevValue = jsonObj[nodeName];
                    jsonObj[nodeName] = [];
                    jsonObj[nodeName].push(prevValue);
                }
                jsonObj[nodeName].push(convertXmlToJson(child));
            }
        }
    }
    return jsonObj;
}

Usage:

var jsonData = JSON.stringify(convertXmlToJson(xmlDocument)); // xmlDocument = XML DOM document

Answer №2

For those looking for a compact solution to convert XML to JSON and vice versa, check out this lesser-known library: https://github.com/abdmob/x2js

Answer №3

If you are open to using jQuery, there is a helpful resource available:

$.get("http://jfcoder.com/test.xml.php", function(xml){
    var json = $.xml2json(xml);
    $('pre').html(JSON.stringify(json)); // Displaying the result in the browser
});

Example XML input:

<nums>
 <num>00597</num>
 <num>0059</num>
 <num>5978</num>
 <num>5.978</num>
</nums>

Expected Output:

{"num":["00597","0059","5978","5.978"]}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to incorporate arrowheads into the lines that have been sketched using canvas

I need assistance with incorporating arrowheads at the end of linear plots drawn on a coordinate grid using my custom function. You can view an example of the current setup in this JsFiddle: https://jsfiddle.net/zje14n92/1/ Below is the code snippet respo ...

Send a JSON object as a stream file in a Node.js REST API

Is there a way to upload a large JSON object directly as a JSON file through REST API without saving it locally? I attempted to save the JSON object to the local file system and then create a read stream from the file for uploading, but I am restricted fr ...

Steps for serving a "noop" document via HTTP

I am in the process of creating a CGI script that performs various functions. I am striving to maintain simplicity and portability within the script. My main objective is to provide users with a way to send a message to the server without losing the curren ...

I keep encountering an error with the Next.js Image component, even though I have properly included the src prop

By passing the src prop to the UserCard component, I am encountering the following error message. Error Unhandled Runtime Error Error: Image is missing required "src" property. Make sure you pass "src" in props to the `next/image` comp ...

Updating the content of a div when the mouse hovers over it

Looking for some help here - I have a few divs with paragraphs of text inside. My goal is to change the text in each div when it's being hovered over. I know this can be done using JavaScript (jquery perhaps?), but my coding skills are pretty basic. A ...

"Configuration parameter stored in a JSON file within the public directory of a Create React App

My public folder contains a file called config.json, and I need to set different parameters for development and production modes. The file is fetched when my app loads using fetch('config.json').then(). Is there a way to structure my config.json ...

Tips for removing ASP.NET MVC controller name from angular route

My ASP.NET MVC login page leads to a different page that is integrated with Angular. After logging in, the URL looks something like this: http://localhost:5083/Home#/home I want to remove the ASP MVC controller name ("Home") from the URL. Is there a ...

jQuery problem causes page to scroll when button is clicked

Is there a way to smoothly scroll to the second section of the page when a button is clicked using jQuery? $('.home_scroll_btn a').on('click', function(){ var scrollPosition = $('#intro-home').offset().top; $( ...

Can you upload a file using the MaterialUI Upload Button in React and then send it to Firestorage?

Hi everyone! I recently implemented MaterialUI's Upload Button in my project, which you can find here: https://material-ui.com/components/buttons/ Below you will see the code snippet where I have integrated this button and now I am trying to upload a ...

Generating and verifying checksums for strings in Node JS: A step-by-step guide

I am in the process of rewriting a function in Node.js for generating and verifying checksums for payment transactions. I am new to coding in Node.js and need some guidance. The code I have received from the Service Provider needs to be converted into Nod ...

What is the best way to remove current markers on google maps?

This is how I implemented it in my project. The issue I'm facing is that the clearAirports function does not seem to clear any existing markers on the map or show any errors in the Google console. googleMaps: { map: null, init: function () { ...

Is it possible to retrieve all data from the Google translation API?

In my React app, the main component contains this function: componentDidMount(){ const land = ["Afrikaans", "Albanian", "Amharic", "Arabic", "Armenian", "Assamese", "Aymara", &qu ...

Incorporate a fresh attribute to the JSON data in an Angular API response

I'm currently working on updating my JSON response by adding a new object property. Below is an example of my initial JSON response: { "products": [{ "id": 1, "name": "xyz" }] } My goal is to include a new object property ca ...

Unlimited scrolling feature in Ionic using JSON endpoint

Trying to create an Ionic list using data from a JSON URL. JSON Code: [{"id":"1","firstName":"John", "lastName":"Doe"}, {"id":"2","firstName":"Anna", "lastName":"Smith"}, {"id":"3","firstName":"Peter", "lastName":"Jones"},{......................}] app.j ...

react component fails to rerender upon state change

I am struggling with a React functional component that includes a file input. Despite selecting a file, the text in the h1 tag does not change from choose file to test. The handleChange function is triggered successfully. A console.log statement confirm ...

Transform the structure of the JSON data object

When I use the fetch() request, a JSON file is displayed. Here's an example of what I receive from the database: [ { "id": 3086206, "title": "General specifications" }, { "id": 3086207, "title": "Features ...

Are you utilizing Google Chrome extensions for importing and exporting JSON files?

Currently, I am in the process of developing a Google Chrome extension and I have a question regarding its capabilities. Is it possible for the extension to generate JSON files for users to download (export) as well as implementing a button that allows use ...

Exploring ways to validate the existence of a class in HTML table elements

If I want to verify if each element has a specific class when creating tables and clicking on the corresponding cells above them, This is what I have tried. However, it did not work as expected. How can I make this work correctly? What am I missing her ...

Acquire information from a JSON formatted string

I am having trouble extracting the first name from the JSON data provided below. While I am able to display the entire string using JavaScript [ alert(data); ], I am struggling to isolate just the first names. Any assistance would be greatly appreciated! ...

Executing Cascading Style Sheets (CSS) within JQuery/Javascript

I've been encountering a problem with my website. I have implemented grayscale filters on four different images using CSS by creating an .svg file. Now, I'm looking to disable the grayscale filter and show the original colors whenever a user clic ...