Reputation: 370
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!
Upvotes: 0
Views: 465
Reputation: 993
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
}
]
}
}
Upvotes: 0
Reputation: 5343
just do:
var A=
{
"test1": "abc",
"b1":
{
"test2": "def",
"collectionOfCType":
[
{
"h": 100,
"w": 200
},
{
"h": 50,
"w": 80
}
]
}
}
Upvotes: 0
Reputation: 736
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
}
Upvotes: 3