Cleaning up unnecessary brackets and excess data in a JSON object using JavaScript

Currently, I am utilizing the following function to parse an XML file:

function xmlToJson(xml) {
    var attr, child, attrs = xml.attributes,
        children = xml.childNodes,
        key = xml.nodeType,
        obj = {},
        i = -1,
        o = 0;
    if (key == 1 && attrs.length) {
        obj[key = o] = {};
        while (attr = attrs.item(++i)) {
            obj[key][attr.nodeName] = attr.nodeValue;
        }
        i = -1;
    } else if (key == 3) {
        obj = xml.nodeValue;
    }
    while (child = children.item(++i)) {
        key = child.nodeName;
        if (obj.hasOwnProperty(key)) {
            if (obj.toString.call(obj[key]) != '[object Array]') {
                obj[key] = [obj[key]];
            }
            obj[key].push(xmlToJson(child));
        } else {
            obj[key] = xmlToJson(child);
        }
    }
    return obj;
}

After parsing the next file, the resulting string (displayed using JSON.stringify) is as follows:

File (omitting the '<' characters as they are not visible, but they are present in the actual file):

?xml version="1.0" encoding="UTF-8" standalone="no"?>
playlist>
vid src="video/intro.mp4" type="video/mp4"/>
vid src="video/intro.mp4" type="video/mp4"/>
/playlist>

Converted to JSON:

{"playlist":{"#text":["\n","\n","\n"],"vid":[{"0":{"src":"video/intro.mp4","type":"video/mp4"}},{"0":{"src":"video/intro.mp4","type":"video/mp4"}}]}}

However, I require the output to be simplified to:

[{"0":{"src":"video/intro.mp4","type":"video/mp4"}},{"0":{"src":"video/intro.mp4","type":"video/mp4"}}]

Apologies for the novice question, as I am new to both JS and JSON, and my experience with them can be counted on one hand.

Thank you in advance.

EDIT: RESOLVED - I resolved the issue by allowing the object to be converted into a string, then using 'substring' to extract the necessary part, and finally converting the remaining string back. Here is the solution:

JSON.parse(JSON.stringify(jsonPlaylist).substring(44,JSON.stringify(jsonPlaylist).length-2));

Assuming jsonPlaylist is the string variable containing the entire parsed XML file.

Answer №1

For the php language:

$yourxmlstring = trim(substr($yourxmlstring, strlen('{"playlist":{"#text":["\n","\n","\n"],"vid":')), -1);

Essentially, I utilized trim and substr to remove unwanted portions.

Now, in javascript:

str.replace(/{"playlist":{"#text":\["\\n","\\n","\\n"\],"vid":/,'').replace(/}+$/,'');

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

Determine if the start_date is greater than the end_date using jQuery

Having a particular issue with date validation. The start_date and end_date are obtained from an HTML form, being chosen using a bootstrap date picker. A sample of the dates looks like this: start_date = 15-06-2016 end_date = 14-06-2016 To verify if th ...

Updating Cart Array in Angular 4 when Adding a New Item

I'm currently using angular 4 and I have encountered an issue in the code where adding a new product to the cart overwrites the existing item instead of appending it to the array. Here is a screenshot illustrating the problem cart.service.ts export ...

Enhance your Rails 5 application with a dynamic live search feature powered by Keyup. Say goodbye to

Currently, I have a Rails 5.1.3 application with a simple contact model that stores names and phone numbers. To enable searching within the index view/page, I am utilizing Ransack. A keyup event listener written in Coffeescript captures user input as they ...

Issues with Angular displaying filter incorrectly

Whenever a user chooses a tag, I want to show only the posts that have that specific tag. For instance, if a user selects the '#C#' tag, only posts with this tag should be displayed. This is how my system is set up: I have an array of blogs that ...

developing a fresh node within the jstree framework

Recently, I have been working on creating a node using crrm as shown below $("#TreeDiv").jstree("create", $("#somenode"), "inside", { "data":"new_node" }); This specific function is triggered by a wizard, enabling me to seamlessly create a new node withi ...

Having trouble with Selenium WebDriverJS on both FireFox and Internet Explorer

Having developed multiple JavaScript tests using chromedriver to run them in Chrome, I am now facing the challenge of running these same tests in FireFox and IE. The test below is functional in Chrome: var assert = require('assert'), test = requ ...

Use Jackson to populate a Plain Old Java Object with an array from the main JSON node

Utilizing Jackson and RESTEasy for integration with an external API has been successful in populating simple objects into POJOs. However, a challenge arises when receiving an array of objects as a response. [ { "variable1": "someValue1", "variab ...

Switch up the link color when it pops up

Is there a method to change the link color to gray without encountering glitches like on my site, where it mistakenly shows "Quick Nav."? Click here to view the page with the glitch I only want this particular link to be bold and not any other links. He ...

The event listener for the custom cursor in Nuxt.js is failing to work properly when the route

I am currently in the process of constructing a new website for our studio, but am encountering difficulties with getting the custom cursor to function correctly. I implemented a custom cursor using gsap, and it worked perfectly; however, once I navigate t ...

Moving various divisions through Javascript by clicking various buttons although sharing the same identifier

I am working with the script below: $(document).ready(function() { $('.expandButton').click(function() { $('.expandableSection').toggle("slide"); }); }); My goal is to apply this script to multiple sections. However, ...

What is the best method for adjusting the text size within a doughnut chart using react-chartjs-2?

Is there a way to adjust the text size within the doughnut chart using react-chartjs-2? I find that the center text appears too small. https://i.stack.imgur.com/QsI0V.png import React, {Fragment} from 'react'; import Chart from 'chart.js&a ...

Exploring SwiftUi's JSON Decoding

Recently I started diving into Swift and SwiftUi, attempting to Decode a JSON file. While familiar with using CodingKeys for decoding, I stumbled on an issue when the key in question is a date. The structure of my JSON appears as follows: { "2020 ...

Problem with Ext.net TabPanel

I am encountering a problem with the Ext.net TabPanel. Every time the page containing the tab panel is opened for the first time after the application has been rebuilt, it throws an error Uncaught TypeError: Object [object Object] has no method 'getCo ...

Struggling to achieve improved results with Ambient Occlusion in three.js

After reviewing the demonstration here . var depthShader = THREE.ShaderLib[ "depthRGBA" ]; var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms ); depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vert ...

Using state in a ReactJS and Rails Ajax request

I am currently working on a ProductItem component that triggers an AJAX post call to create a basket item when the user clicks 'Add to Basket'. Despite setting state correctly in the Product Item component, I am facing an issue where I am unable ...

Even with the text field populated and clearly existing, Firefox is still throwing a null error when trying to retrieve it using

Hey there! I'm currently working on a sample HTML page and I'm facing an issue with retrieving data from a text field. No matter what I try, I keep encountering the following error: TypeError: document.getElementById(...) is null Let me share t ...

Issue: The type 'void' cannot be assigned to the type 'ReactNode' in the array.map() function

Having trouble with my function call error within the practice setup in App.tsx. My expectation of array.map() being compatible with TypeScript seems to be incorrect. The generated HTMLElement from this map is not displaying on screen. Any suggestions on ...

Maintain original image file name when downloading

I have successfully created a download link containing a base 64 encoded image. The only issue is that I need to retain the original file name, which is dynamic and cannot be hardcoded. downloadImage: function(){ var image_url = document.getEleme ...

"Integrating auto-expandable rows and subrows into a React table with the use

Presented here is my code for a React table using hooks. I encountered a challenge when trying to set all rows and subrows to be expanded by default upon opening the page. Despite attempting various solutions, none of them proved successful. Check out the ...

How to extract query string parameters using node.js

I'm currently working on fetching query string parameters from a URL using the node.js restify module. This is an example of the URL I am dealing with: Here is the relevant code snippet: server.use(restify.bodyParser()); server.listen(7779, functi ...