2009-05-15 19 views
7

Tengo algunos JSON devuelto al navegador como este "producto":Principiante JavaScript: Trabajar con JSON y objetos en JavaScript

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

Quiero la información proporcionada es un objeto "producto" para que pueda utilizar prototipo métodos como un toHTMLImage() que devuelve una representación de imagen HTML del producto:

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

¿Cómo convierto mis resultados JSON en un objeto Product de modo que pueda utilizar toHTMLImage?

Respuesta

18

simple, si lo tengo,

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]; 

No estoy seguro si esto va a funcionar, pero darle un tiro:

var stuff = { "Title": "School Bag", "Image": "/images/school-bag.jpg" } 
stuff.prototype = Product; 
+0

Probar: cosas .__ proto__ = Product.prototype; –

0

Para convertir JSON en un objeto, puede usar window.JSON.parse(jsonText) en M ozilla (compruebe Chrome y Opera, no sé cómo funciona allí.)

En Internet Explorer puede usar (new Function("return " + jsonText))(), pero debe verificar el JSON para ver si hay símbolos no válidos, googleéelo.