Beginner [removed] Working with JSON and Objects in JavaScript

前端 未结 4 1877
失恋的感觉
失恋的感觉 2020-12-31 19:31

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

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

I want

相关标签:
4条回答
  • 2020-12-31 19:54

    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.

    0 讨论(0)
  • 2020-12-31 19:57

    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
    
    0 讨论(0)
  • 2020-12-31 20:01
    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;
    
    0 讨论(0)
  • 2020-12-31 20:16

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

    0 讨论(0)
提交回复
热议问题