0

I want to create a json object in javascript/jquery. For this Class A i want its json object.

Class A
{
string test1;
B b1;
}

Class B
{
string test2;
List< C> collectionOfCType;
}

Class C
{
  int h;int w;
}

Inside my js- I am able to get json object having value of test1 of A but b1 value is showing undefined.

var A=
    {
        "test1": "abc",
        "b1": B
    }

var B =
    {
        "test2": "def",
        ... so on ..
     }

Please help!

1
  • Is b1 supposed to be an instance of B? Where do you construct these objects, where does the string "abc" come from? Commented Nov 20, 2013 at 13:30

3 Answers 3

3

You need change the order because when you declare var A the variable B even isn`t defined

var B =
    {
        "test2": "def",
        ... so on ..
     }

var A=
    {
        "test1": "abc",
        "b1": B
    }
Sign up to request clarification or add additional context in comments.

Comments

0

just do:

var A=
    {
        "test1": "abc",
        "b1":
        {
            "test2": "def",
            "collectionOfCType":
                [
                    {
                        "h": 100,
                        "w": 200
                    },
                    {
                        "h": 50,
                        "w": 80
                    }
                ]
        }
    }

Comments

0

Here's a way to model and debug this:

I encapsulated the code in a function scope so that it cannot step on global variable A, B, and C.

Also added exception reporting to catch some syntax errors when playing with changes to the code.

As you move the order of declarations you will find that you can get partially initialized data structures, as @Guilherme pointed out before me.

Also, the quoting of properties is not necessary in JavaScript, JSON.stringify will do so for you.

Code

(function() {
    try {
        var C = {
            h: 4,
            w: 3
        };
        var cArray = [
            C, 
            C, 
            C];
        var B = {
            test2: "def",
            arrayOfC: cArray
        };
        var A = {
            test1: "abc",
            b1: B
        };
        console.log(JSON.stringify(A, null, 2));
        // window.alert(JSON.stringify(A, null, 2));
    } catch (exception) {
        console.error(exception.stack);
    }
})();

Output

{
  "test1": "abc",
  "b1": {
    "test2": "def",
    "arrayOfC": [
      {
        "h": 4,
        "w": 3
      },
      {
        "h": 4,
        "w": 3
      },
      {
        "h": 4,
        "w": 3
      }
    ]
  }
}

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.