chniter / bstreeview

Bootstrap Treeview, A very simple plugin to build a basic and elegant Treeview with bootstrap 4. See the demo:
https://chniter.github.io/bstreeview/
Apache License 2.0
367 stars 53 forks source link

json as string #32

Closed Kurtaja closed 1 year ago

Kurtaja commented 1 year ago

I've tried the this library and it looks great. I'm able to get the example in github to show the demo three. And when I change the json variable it updates correspondingly. E.g. this code shows up fine:

        let myJsonVar = [{ text: "Inbox", icon: "fa fa-inbox fa-fw" }]
        $('#myTree').bstreeview({
            data: myJsonVar,
            expandIcon: 'fa fa-angle-down fa-fw',
            collapseIcon: 'fa fa-angle-right fa-fw',
            indent: 1.25,
            parentsMarginLeft: '1.25rem',
            openNodeLinkOnNewTab: true
        });

However, in my program, the three comes in string form, so I thought I could just invoke 'parseJSON() to convert it. But for some reason it does not work:

        let sTxt = '[{ text: "Inbox", icon: "fa fa-inbox fa-fw" }]';
        let myJsonVar = parseJSON(sTxt);
        $('#myTree').bstreeview({
            data: myJsonVar,
            expandIcon: 'fa fa-angle-down fa-fw',
            collapseIcon: 'fa fa-angle-right fa-fw',
            indent: 1.25,
            parentsMarginLeft: '1.25rem',
            openNodeLinkOnNewTab: true
        });

It should be such a dead easy thing, and I feel really bad posting for it, but I've really spent much time looking for the hidden trick (stringify, with following parseJSON or even two times parseJSON as I've seen some suggesting in other posts, the jQuery version, $.parseJSON, adding quotes to the key, etc.) Has anybody else encountered this problem or is it only me having two left hands?

Kurtaja commented 1 year ago

Found out of this myself, and indeed was dead easy as I thought, and even embarrasing. Anyhow, in case anybody else out there are js novice, and as head less as I can be, the solution was the single quotes in the start and end of the string. The way I found out of it was using try /catch (voila dead easy ... and embarrasing). Sorry for having cluttered your issues thread with this: try { ... let myJsonVar = parseJSON(sTxt); ... } catch (e) { alert(e); }