Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JSON String into a Particular Object Prototype in JavaScript

I know how to parse a JSON String and turn it into a JavaScript Object. You can use JSON.parse() in modern browsers (and IE9+).

That's great, but how can I take that JavaScript Object and turn it into a particular JavaScript Object (i.e. with a certain prototype)?

For example, suppose you have:

function Foo()
{
   this.a = 3;
   this.b = 2;
   this.test = function() {return this.a*this.b;};
}
var fooObj = new Foo();
alert(fooObj.test() ); //Prints 6
var fooJSON = JSON.parse({"a":4, "b": 3});
//Something to convert fooJSON into a Foo Object
//....... (this is what I am missing)
alert(fooJSON.test() ); //Prints 12

Again, I am not wondering how to convert a JSON string into a generic JavaScript Object. I want to know how to convert a JSON string into a "Foo" Object. That is, my Object should now have a function 'test' and properties 'a' and 'b'.

UPDATE After doing some research, I thought of this...

Object.cast = function cast(rawObj, constructor)
{
    var obj = new constructor();
    for(var i in rawObj)
        obj[i] = rawObj[i];
    return obj;
}
var fooJSON = Object.cast({"a":4, "b": 3}, Foo);

Will that work?

UPDATE May, 2017: The "modern" way of doing this, is via Object.assign, but this function is not available in IE 11 or older Android browsers.

like image 338
BMiner Avatar asked May 03 '11 17:05

BMiner


People also ask

How do I parse a JSON string in JavaScript?

Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.

Which method converts a JSON string to a JavaScript object?

parse() JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON. parse() , as the Javascript standard specifies.

How should you convert this string into a JavaScript object?

JSON text/object can be converted into Javascript object using the function JSON. parse(). If we pass a invalid JSON text to the function JSON. parse(), it will generate error (no output is displayed when using in tag of HTML).


3 Answers

See an example below (this example uses the native JSON object). My changes are commented in CAPITALS:

function Foo(obj) // CONSTRUCTOR CAN BE OVERLOADED WITH AN OBJECT
{
    this.a = 3;
    this.b = 2;
    this.test = function() {return this.a*this.b;};

    // IF AN OBJECT WAS PASSED THEN INITIALISE PROPERTIES FROM THAT OBJECT
    for (var prop in obj) this[prop] = obj[prop];
}

var fooObj = new Foo();
alert(fooObj.test() ); //Prints 6

// INITIALISE A NEW FOO AND PASS THE PARSED JSON OBJECT TO IT
var fooJSON = new Foo(JSON.parse('{"a":4,"b":3}'));

alert(fooJSON.test() ); //Prints 12
like image 45
Oliver Moran Avatar answered Oct 19 '22 04:10

Oliver Moran


The current answers contain a lot of hand-rolled or library code. This is not necessary.

  1. Use JSON.parse('{"a":1}') to create a plain object.

  2. Use one of the standardized functions to set the prototype:

    • Object.assign(new Foo, { a: 1 })
    • Object.setPrototypeOf({ a: 1 }, Foo.prototype)
like image 182
Erik van Velzen Avatar answered Oct 19 '22 02:10

Erik van Velzen


Do you want to add JSON serialization/deserialization functionality, right? Then look at this:

You want to achieve this:

UML

toJson() is a normal method.
fromJson() is a static method.

Implementation:

var Book = function (title, author, isbn, price, stock){
    this.title = title;
    this.author = author;
    this.isbn = isbn;
    this.price = price;
    this.stock = stock;

    this.toJson = function (){
        return ("{" +
            "\"title\":\"" + this.title + "\"," +
            "\"author\":\"" + this.author + "\"," +
            "\"isbn\":\"" + this.isbn + "\"," +
            "\"price\":" + this.price + "," +
            "\"stock\":" + this.stock +
        "}");
    };
};

Book.fromJson = function (json){
    var obj = JSON.parse (json);
    return new Book (obj.title, obj.author, obj.isbn, obj.price, obj.stock);
};

Usage:

var book = new Book ("t", "a", "i", 10, 10);
var json = book.toJson ();
alert (json); //prints: {"title":"t","author":"a","isbn":"i","price":10,"stock":10}

var book = Book.fromJson (json);
alert (book.title); //prints: t

Note: If you want you can change all property definitions like this.title, this.author, etc by var title, var author, etc. and add getters to them to accomplish the UML definition.

like image 44
Gabriel Llamas Avatar answered Oct 19 '22 03:10

Gabriel Llamas