Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Beginner JavaScript: Working with JSON and Objects in JavaScript

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?

like image 620
eddiegroves Avatar asked May 15 '09 00:05

eddiegroves


3 Answers

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
like image 177
José Leal Avatar answered Oct 20 '22 11:10

José Leal


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;
like image 42
Evert Avatar answered Oct 20 '22 13:10

Evert


Maybe this page will be usefull : http://www.json.org/js.html

like image 39
Boris Guéry Avatar answered Oct 20 '22 12:10

Boris Guéry