2009-05-15 7 views
7

ho qualche JSON restituita al browser come questo "prodotto":Principiante JavaScript: Lavorare con JSON e oggetti in JavaScript

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

voglio questi dati per essere un oggetto "Prodotto" in modo da poter usare prototipo metodi come un toHTMLImage() che restituisce una rappresentazione HTML immagine del prodotto:

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

Come posso convertire i miei risultati JSON in un oggetto Product in modo che posso usare toHTMLImage?

risposta

18

Semplice, se ho capito,

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

Non sono sicuro se questo funzionerà, ma dare un colpo:

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

Prova: stuff .__ proto__ = Product.prototype; –

0

Per convertire JSON in un oggetto è possibile utilizzare window.JSON.parse(jsonText) in M ozilla (controlla Chrome e Opera, non so come funziona lì.)

In Internet Explorer è possibile utilizzare (new Function("return " + jsonText))(), ma è necessario controllare il JSON per simboli non validi, google it.