Generate a JSON from a converted XML with Javascript

Asked

Viewed 1,176 times

1

I was able to convert an xml to json using a solution that I found on the Internet and served me perfectly, it stores all the json in a string and shows on the screen, but I don’t know how to play the contents of this string in a.json file

Follow the code of my index.html:

<!doctype html>
<html>

<head>
    <title>Gerar Json</title>
    <script type="text/javascript" src="xml2json.js"></script>
</head>

<body>
    <pre id="jsnstr"></pre>
    <script type="text/javascript">
        var jsonstr = xml2json.fromFile('arquivo.xml', 'string');
        document.getElementById('jsnstr').innerHTML = jsonstr;
    </script>
</body>

</html>

Javascript code that converts xml to json:

// Converts XML to JSON
// from: http://coursesweb.net/javascript/convert-xml-json-javascript_s2
function XMLtoJSON() {
    var me = this; // stores the object instantce

    // gets the content of an xml file and returns it in 
    me.fromFile = function(xml, rstr) {
        // Cretes a instantce of XMLHttpRequest object
        var xhttp = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
        // sets and sends the request for calling "xml"
        xhttp.open("GET", xml, false);
        xhttp.send(null);

        // gets the JSON string
        var json_str = jsontoStr(setJsonObj(xhttp.responseXML));

        // sets and returns the JSON object, if "rstr" undefined (not passed), else, returns JSON string
        return (typeof(rstr) == 'undefined') ? JSON.parse(json_str) : json_str;
    }

    // returns XML DOM from string with xml content
    me.fromStr = function(xml, rstr) {
        // for non IE browsers
        if (window.DOMParser) {
            var getxml = new DOMParser();
            var xmlDoc = getxml.parseFromString(xml, "text/xml");
        } else {
            // for Internet Explorer
            var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async = "false";
        }

        // gets the JSON string
        var json_str = jsontoStr(setJsonObj(xmlDoc));

        // sets and returns the JSON object, if "rstr" undefined (not passed), else, returns JSON string
        return (typeof(rstr) == 'undefined') ? JSON.parse(json_str) : json_str;
    }

    // receives XML DOM object, returns converted JSON object
    var setJsonObj = function(xml) {
        var js_obj = {};
        if (xml.nodeType == 1) {
            if (xml.attributes.length > 0) {
                js_obj["@attributes"] = {};
                for (var j = 0; j < xml.attributes.length; j++) {
                    var attribute = xml.attributes.item(j);
                    js_obj["@attributes"][attribute.nodeName] = attribute.value;
                }
            }
        } else if (xml.nodeType == 3) {
            js_obj = xml.nodeValue;
        }
        if (xml.hasChildNodes()) {
            for (var i = 0; i < xml.childNodes.length; i++) {
                var item = xml.childNodes.item(i);
                var nodeName = item.nodeName;
                if (typeof(js_obj[nodeName]) == "undefined") {
                    js_obj[nodeName] = setJsonObj(item);
                } else {
                    if (typeof(js_obj[nodeName].push) == "undefined") {
                        var old = js_obj[nodeName];
                        js_obj[nodeName] = [];
                        js_obj[nodeName].push(old);
                    }
                    js_obj[nodeName].push(setJsonObj(item));
                }
            }
        }
        return js_obj;
    }

    // converts JSON object to string (human readablle).
    // Removes '\t\r\n', rows with multiples '""', multiple empty rows, '  "",', and "  ",; replace empty [] with ""
    var jsontoStr = function(js_obj) {
        var rejsn = JSON.stringify(js_obj, undefined, 2).replace(/(\\t|\\r|\\n)/g, '').replace(/"",[\n\t\r\s]+""[,]*/g, '').replace(/(\n[\t\s\r]*\n)/g, '').replace(/[\s\t]{2,}""[,]{0,1}/g, '').replace(/"[\s\t]{1,}"[,]{0,1}/g, '').replace(/\[[\t\s]*\]/g, '""');
        return (rejsn.indexOf('"parsererror": {') == -1) ? rejsn : 'Invalid XML format';
    }
};

// creates object instantce of XMLtoJSON
var xml2json = new XMLtoJSON();

XML example:

<a>
    <child id='MNU1' />
    <child id='MNU2'/>
    <child id='MNU3'/>
    <child id='MNU4'/>
    <child id='MNU5'/>
    <child id='MNU6'/>
    <child id='MNU7'/>
    <child id='MNU8'/>
</a>

I have this problem at the moment and I haven’t found any solution so far.

2 answers

2


"play the contents of this string in a.json file"

You nay can save because the script is running on the client, for security reasons you do not have access to automatically save files on it.

You have some options to save data in the browser:

Localstorage

You can store data on customer machine like this:

var data = { name: 'Bob', age: 12 };
Window.localStorage.setItem('person', data);

Then on a different page on the same domain, you can then recover that data:

var data = Window.localStorage.getItem('person');

However, note that some browser security settings disable localStorage so that it doesn’t work in all situations.

One more reading here:

Using_the_web_storage_api

Window.localStorage

Cookies

The other alternative is to use cookies .

document.cookie = "name=Bob";
document.cookie = "age=12";
console.log(document.cookie); // displays: name=Bob;age=12

One more reading here:

cookie

--

You can also generate a file and request "save as" to the user.

You can use the lib Filesaver.js

Example

  • Wow, I didn’t think of that, hehe. Do I then have to use a php for example to generate the file I want from that variable ?

  • @Wesleybrito. So it will depend on your need, why you want this JSON?

  • basically I will read this Json to generate some angular screens with the contents of this json, thinking of a grosser way I came up with this question of creating json files from some xmls.

  • Want to save this JSON to the server?

  • yes, for now it is in local development but it will probably stay on a Node server.

  • You will have to save this file with Server-side language. a PHP solves your problem :)

  • OK, thanks for the help.

Show 2 more comments

0

I found an online code that I think can help:

function xmlToJson(xml) {

    // Create the return object
    var obj = {};

    if (xml.nodeType == 1) { // element
        // do attributes
        if (xml.attributes.length > 0) {
        obj["@attributes"] = {};
            for (var j = 0; j < xml.attributes.length; j++) {
                var attribute = xml.attributes.item(j);
                obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
            }
        }
    } else if (xml.nodeType == 3) { // text
        obj = xml.nodeValue;
    }

    // do children
    if (xml.hasChildNodes()) {
        for(var i = 0; i < xml.childNodes.length; i++) {
            var item = xml.childNodes.item(i);
            var nodeName = item.nodeName;
            if (typeof(obj[nodeName]) == "undefined") {
                obj[nodeName] = xmlToJson(item);
            } else {
                if (typeof(obj[nodeName].push) == "undefined") {
                    var old = obj[nodeName];
                    obj[nodeName] = [];
                    obj[nodeName].push(old);
                }
                obj[nodeName].push(xmlToJson(item));
            }
        }
    }
    return obj;
};

And then it converts like this:

var jsonConverted = JSON.stringify(xmlToJson(xmlDoc));

For more information click HERE

  • pedro this code Voce sent me it just already does what I already have, my code already generates a json I want to put the content of the string that is storing the json inside a.json file.

  • Voce can use the pound fs to write a json http://jsbin.com/rizifasaji/edit?js,console

  • where you find this library ?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.