I am very new to JS, have been working in C/C++ before,
I need an equivalent of below C structure in JSON
struct tmp_t{
int a;
char c_str[1024];
};
struct tmp2_t{
int a2;
.
.
char c2_str[1024];
};
struct my {
int number;
struct tmp_t tmp[100];
struct tmp2_t tmp2[100][1000];
};
For a json like
var myJSON = {
"number":0,
.
.
};
I need to access it like
myJSON.tmp[0].a = 10;
myJSON.tmp2[0][1].c2_str = "hello world"
any input is highly appreciated
Javascript properties are not typed like they are in C so there is no purely “equivalent” expression in javascript. You don’t predeclare typed data structures like your C code has. I given variable or property in javascript can be assigned any value or reference – there is not hard typing. So without variables that can only contain a specific type like C has, there’s no pre-declaring of data structure definitions like you have included from C.
Instead, you just declare the properties you want to use on a live object or if you intend to use many of them, you can create a prototype which you can instantiate when needed.
A direct declaration of a live object instance somewhat like your last structure would look like this:
This would declare an object named
mythat had three properties callednumber,tmpandtmp2.numberinitially contained the number10and the other two properties contained arrays of length 100 who’s values wereundefined. I don’t know of any compact way to predefine your two dimensional array in javascript without running code in a loop to initialize it.This data defintion would let you access
my.number,my.tmpand so on.If you want your arrays to contains objects with properties themselves, then you need to populate those arrays with the objects.
Or, in code, you could add in item to the tmp array with code like this:
Or, you could create the object separately and then put it in the array:
Or, you could assign each property individually like this:
In either case, you could then access the data like this: