0

I have a string <ul><li e="100" n="50">Foo</li><li e="200" n="150">Bar</li></ul> and on client side I have to convert it to JSON. Something like {data:['Foo','Bar'],params:['100;50','200;150']}

I found a pretty good way to achieve it in here so my code should be something like that

var $input = $(input);
var data = "data:[";
var params = "params:[";

var first = true;
$input.find("li").each(function() {
    if (!first) {
        data += ",";
        params += ",";
    } else {
        first = false;
    }
    data += "'" + $(this).text() + "'";
    var e = $(this).attr("e");
    var n = $(this).attr("n");
    params += "'" + e + ';' + n + "'";
});

return "{data + "]," + params + "]}";

But the problem is that I can't use jquery. How can I do the same thing with prototype?

2 Answers 2

2

You want to use a DOM parser:

https://developer.mozilla.org/en/DOMParser

Something like this...

var xmlStr = '<ul><li e="100" n="50">Foo</li><li e="200" n="150">Bar</li></ul>';

var parser = new DOMParser();
var doc = parser.parseFromString(xmlStr, "application/xml");

var rootElement = doc.documentElement;
var children = rootElement.childNodes;

var jsonObj = {
    data: [],
    params: []
};

for (var i = 0; i < children.length; i++) {
    // I realize this is not how your implementation is, but this should give
    // you an idea of how to work on the DOM element
    jsonObj.data.push( children[i].getAttribute('e') );
    jsonObj.params.push( children[i].getAttribute('n') );
}

return jsonObj.toJSON();

Also, don't manually build your JSON string. Populate an object, then JSON-encode it.

Edit: Note that you need to test for DOMParser before you can use it. Check here for how you can do that. Sorry for the W3Schools link.

Sign up to request clarification or add additional context in comments.

Comments

0

Why you are building an array object with string? Why not

var data = new Array();
var params = new Array();

$$("li").each(function() {
    data.push ($(this).text());
    params.psuh($(this).attr("e") + ";" + $(this).attr("n"));
});


return {data:data.toString(), params:params.toString()};

or

return {data:data, params:params};

3 Comments

Yes, but it still requires jQuery and I can use only PrototypeJS
Try using $$, Here is a reference for it: api.prototypejs.org/dom/dollar-dollar $$('div') === document.getElementsByName('div')
Sorry I misunderstood your problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.