1

Assuming I have a JavaScript function like this...

function Object1() {
  this.var1;
  this.var2;
  this.var3;

  this.method1 = function() {
    this.var3 = this.var1 + this.var2;
  }
}

...and create an instance:

var obj1 = new Object1();
obj1.var1 = 1;
obj1.var2 = 2;
obj1.method1();

Based on obj1, I want to create a JSON string from all instance variables of function Object1. Obviously, the expected JSON string should look as follows:

{"var1" : 1, "var2" : 2, "var3" : 3}

Two Questions:

1.) Is there a more elegant way to manually implementing a to_json() method in function Object1 which creates a JSON object of all instance variables and calls JSON.stringify() on that JSON object?

2.) In this regard, is there a more elegant way to create an instance of function Object1 based on a JSON string exemplarily shown above to manually implementing a from_json() method on function Object1 which calls JSON.parse() on that JSON string, iterates over the resulting JSON object and assigns each JSON value to the respective instance variable.

3
  • 2
    I think for (var prop in MyObject) { ... } would work, though I'm not sure "foreach"s are supported in all JS implementations. (Docs on For...In) Commented Feb 13, 2011 at 3:56
  • 3
    Re: 1) I'm not seeing what a handwritten to_json implementation would give you over JSON.stringify(obj1). The serializer works fine on your Object1 instances, and knows to skip functions. What is inelegant? Commented Feb 13, 2011 at 5:26
  • JSON.stringify doesn't handle multidimensional array/object. How do you do that? Commented Feb 26, 2011 at 3:09

1 Answer 1

1

i am not sure why you want custom to_json and from_json methods but if you want to just get the details of public variables of an object with its data then you can use JSON.stringify without any problem and it will also handle nesting of the objects, like this

function Object1() {
  this.var1;
  this.var2;
  this.var3;
  this.var4;

  this.method1 = function() {
    this.var3 = this.var1 + this.var2;
  }
}

var obj1 = new Object1();
obj1.var1 = 1;
obj1.var2 = 5;
obj1.var4 = new Object1();
obj1.var4.var1 = 2;
obj1.var4.var2 = 3;
obj1.method1();
obj1.var4.method1();

JSON.stringify(obj1);

so after executing this you will get "{"var1":1,"var2":5,"var4":{"var1":2,"var2":3,"var3":5},"var3":6}"

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.