Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

OK, so I'm facing this challenge...

Here's how javascript console (in Chrome) prints my object :

enter image description here

And here's what I'd like to do :

var items = [
    { 
        text: "http://www.imdb.com/title/tt0106307/",
        children: [
             { text: "Director", children: [ { text: "Emir Kusturica" } ] },
             { text: "Title", children: [ { text: "Arizona Dream" } ] }
        ]
    },
    { 
        text: "http://www.imdb.com/title/tt0110074/",
        children: [
             { text: "Director", children: [ { text: "Joel Coen" }, { text: "Ethan Coen"} ] },
             { text: "Title", children: [ { text:"The Hudsucker Proxy" } ] }
        ]
    }
    // and so on..
];

How can I do that? Any ideas/pointers to help me get there?

It should definitely be rather simple, but Javascript is definitely not my thing at all...


P.S. This whole object thing is created after a $.parseJSON(myJson) command - now, don't ask me why it's not converted to a simple nested array and it turns into an object instead... I wish I knew... (not that it'd have the desired structure, but at least it would make more sense)


UPDATE:

OK, and - in case it is helpful - here's my original Json :

{
    "http:\/\/www.imdb.com\/title\/tt0106307\/": {
        "Title": "Arizona Dream",
        "Year": null,
        "Director": "Emir Kusturica"
    },
    "http:\/\/www.imdb.com\/title\/tt0112883\/?ref_=tt_rec_tt": {
        "Title": "Don Juan de Marco",
        "Year": null,
        "Director": "Jeremy Leven"
    },
    "http:\/\/www.imdb.com\/title\/tt0106387\/?ref_=tt_rec_tt": {
        "Title": "Benny & Joon",
        "Year": null,
        "Director": "Jeremiah S. Chechik"
    },
    "http:\/\/www.imdb.com\/title\/tt0099487\/?ref_=tt_rec_tt": {
        "Title": "\u039f \u03a8\u03b1\u03bb\u03b9\u03b4\u03bf\u03c7\u03ad\u03c1\u03b7\u03c2",
        "Year": null,
        "Director": "Tim Burton"
    },
    "http:\/\/www.imdb.com\/title\/tt0354899\/?ref_=tt_rec_tt": {
        "Title": "La science des r\u00eaves",
        "Year": null,
        "Director": "Michel Gondry"
    },
    "http:\/\/www.imdb.com\/title\/tt0110074\/?ref_=tt_rec_tt": {
        "Title": "The Hudsucker Proxy",
        "Year": null,
        "Director": [
            "Joel Coen",
            "Ethan Coen"
        ]
    }
}

P.S. (2) What I'm actually trying to do is to simply represent a Json object as a tree using jsTree, and pushing myself to achieve its desired structure.

share|improve this question
add comment

5 Answers

In ES5 (so will need a shim if supporting IE 8):

function transformToTextNodeTree(obj) {
  return Object.keys(obj).map(function(key) {
    var result = { text: key };
    if (Array.isArray(obj[key]) {
        result.children = obj[key].map(transformToTextNodeTree);
    } else if (typeof obj[key] === "object" && !(obj[key] == null)) {
      result.children = transformToTextNodeTree(obj[key]);
    } else {
      result.children = [createTextNode(obj[key])];
    }
    return result;
  })
}

function createTextNode(val) {
  return { text: val };
}

So what is it doing?

First, we create an array of all of the ownProperties of the object being passed in using Object.keys. We then map over the resulting array of key values and transform them into objects in the form {text, [...children]}.

The actual guts of our mapping function is a recursive function (it calls itself when it encounters an array or an object) that maps the key to the text field of the resulting object, and maps any children to the children field (and, as noted before, it does this recursively).

share|improve this answer
    
I tried a var items = transformToTextNodeTree($.parseJSON(myJson)); and it throws a Uncaught TypeError: Object.keys called on non-object error... Any ideas? (The error is pointing to the Object.keys(obj) part. –  Dr.Kameleon Feb 9 at 13:31
    
@Dr.Kameleon - I was not handling null - that is now fixed :-) –  Sean Vieira Feb 9 at 13:40
add comment

I may be wrong but I believe json is built into javascript. You should be able to say:

var object = eval("<jsoncode>");

where < jsoncode> is the string version of your json

It is possible that I am reading your problem wrong so please give feedback

share|improve this answer
add comment

After you parse JSON, you can try this:

var movieArr = [];
$.each(data, function(index, value) {
    var movie = {
        text: index,
        children: [
            { text: "Director", children: [ { text: value.Director } ] },
            { text: "Title", children: [ { text: value.Title } ] }
        ]
    };   
    arr.push(movie)
});
share|improve this answer
    
The sub-fields will not necessarily be Director and Title. There may many different ones, and with infinite nesting. So, this is obviously a too localized solution. –  Dr.Kameleon Feb 9 at 13:34
add comment

Try this:

// json - source JSON;
var result = [];
for (var url in json) {
    var el = json[url];
    var kids = [];
    for (var prop in el) {
        var v = el[prop];
        if (!v.length) v = [v];
        var subkids = [];
        for (var i in v) subkids.push({text: v[i]});
        kids.push({text: prop, children: subkids});
    }
    result.push({text: url, children: kids});
}
share|improve this answer
add comment

OK, and here's how I've managed to do it - inspired by your answers :-)

function convertJson(node)
{
    var result = [];
    $.each(node, function(key,value)
        {   
            var ch;

            if (($.type(value)!=="string")&&(value!=null)) ch = convertJson(value);
            else ch = [ { text: value }];

            var item =
            {
                text: key,
                children: ch

            };
            result.push(item);
        }
    )

    return result;
}

And yep, it works!

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.