7

I have some JSON returned to the browser like this "product":

{ "Title": "School Bag", "Image": "/images/school-bag.jpg" }

I want this data to be a "Product" object so I can use prototype methods like a toHTMLImage() that returns a HTML image representation of the product:

function Product() { }
Product.prototype.toHTMLImage = function() { //Returns something like <img src="<Image>" alt="<Title>" /> }

How do I convert my JSON results into a Product object so that I can use toHTMLImage?

3 Answers 3

19

Simple, if I got it,

var json = { "Title": "School Bag", "Image": "/images/school-bag.jpg" }
function Product(json) {
    this.img = document.createElement('img');
    this.img.alt = json.Title;
    this.img.src = json.Image;

    this.toHTMLImage = function() {
        return this.img;
    }
}

var obj = new Product(json); // this is your object =D
2
var stuff = { "Title": "School Bag", "Image": "/images/school-bag.jpg" }
var newstuff = new Product();
for(i in stuff) newstuff.i = stuff[i];

Not sure if this will work, but give it a shot:

var stuff = { "Title": "School Bag", "Image": "/images/school-bag.jpg" }
stuff.prototype = Product;
1
  • Try: stuff.__proto__ = Product.prototype; Commented Apr 29, 2010 at 8:33
0

For converting JSON to an object you can use window.JSON.parse(jsonText) in Mozilla (check Chrome and Opera, I don't know how it works there.)

In Internet Explorer you can use (new Function("return " + jsonText))(), but you should check the JSON for non-valid symbols, google it.

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.