1

I am returning JSON from an API via a $.ajax request and end up with a lump of JSON:

var result = {  
  "status": 200,  
  "offset": 5,  
  "limit": 25,
  "total": 7,
  "url": "/v2/api/dataset/topten?",
  "results": [
    {
      "datasets": [
        "dataset",
        "tt_all"
      ],
      "id": "Hxb6VtpFRQ9gEr",
      "title": "Venues",
      "type": "topten",
      "url": "/v2/dataset/topten/Hxb6VtpFRQ9gEr"
        },
    }

Or something similar. There are nested arrays containing more results in larger requests.

I would like to parse this information, put it into an object and have methods for available for that object to extract specific bits of information, from all levels - something like:

result.title => "Venues" or result.id => "Hxb6v...."

However, the output from the AJAX request can be assigned to a var by a user defined so I would like to make a function to stick this in an object with methods available before it exits the ajax success function and get assigned to result or whatever.

I don't particularly want to go down the:

Object.prototype.method = function(){ // extend Object here }  

method as it makes people angry.

If I make another object to extend the prototype:

function Datalump(){};  

Datalump.prototype.title = function(){
// get title or something here
};

I am struggling with what to pass to what and assigning things to the wrong thing.

How do I go about this method / object creation?

Any suggestions or pointers would be greatly appreciated.

UPDATE: Thank you all for the help - it's been very enlightening. I've marked Mike Brant's answer as correct as it seems the most appropriate to the question I asked. George Jempty's answer was also a very useful learning experience.

I'm actually going in a slightly different direction in the project (new requirements!), but parts of all the answers will probably make it into the 'alpha'.

Many thanks all.

5
  • 3
    Why not put it in the object itself? Commented Sep 16, 2013 at 16:26
  • "the output from the AJAX request can be assigned to a var by a user defined" - can you show us how that is done? Sounds like you're actually not receiving JSON, but do something JSONP-like. Commented Sep 16, 2013 at 16:36
  • you can use call to turn an object into "this" inside a function. so, you can use MyCon.call(jsonOb), and put this.method=... inside the MyCon function, and have everything work about like a "real" constructor. Commented Sep 16, 2013 at 16:38
  • @Bergi - it is JSON from the API I'm using, but it gets parsed when returned. Sorry, I really struggled putting the problem into words! Commented Sep 17, 2013 at 8:03
  • @Swooop: Try put the situation into code then - post the one you already have, please. Commented Sep 17, 2013 at 14:57

2 Answers 2

3

If you have a javascript object (like you get after your JSON is parsed into object), you can just add whatever methods you want to it like this:

result.getTitle = function() {
    // return title value of interest
    return this.results.title;
}

result.getId = function() {
    // return id value of interest
    return this.results.id;
}

Here result is the the object that you have after JSON is parsed.

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

1 Comment

Cool, that works, I'm just looking for a way to make it independant of the 'result' bit, so whatever variable the object is assigned to has the methods available.
1

Create a module that wraps the JSON result. The module will return the original result, plus any convenience methods you might need in addition. Then use underscore.js and in particular _.result to interact with the wrapped result. This way you won't need to care whether you are accessing one of the original properties of the wrapped result or one of the convenience methods.

var wrappedResult = WrappedResult(result);
var status = _.result(wrappedResult, 'status');
var foobar = _.result(wrappedResult, 'foobar');

If the convenience of _.result is outweighed by the verbosity, you can just call wrappedResult.status or wrappedResult.foobar() directly

Implementation of WrappedResult:

var WrappedResult = function(result) {
    return _.extend({}, result, {
        foobar: function() {
            console.log('foobar');
        }
    }
}

Something like the above anyway; you might want to extend _.clone(result) instead.

BTW underscore.js is by no means necessary, though in this case it does a nice job of describing exactly what you are doing (you "_.extend" the result with some methods in addition to the initial properties). Instead, wrap your result with an object, and then add methods directly, similar to the other answer:

var WrappedResult = function(result) {
    result.foobar = function() {
        console.log('foobar');
    };

    return result;
}

2 Comments

Ah, I think this is the direction I need to go in. I was trying to stay away from adding too many frameworks/dependancies but this does look useful.
underscore.js is a fantastic library that can be used for so many other purposes

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.