C structure to JSON

C structure to JSON

本文关键字:JSON to structure      更新时间:2023-09-26

我是JS的新手,以前一直在C/C++工作,我需要在 JSON 中等效的 C 结构

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];
};

对于像这样的 json

var myJSON = {
"number":0,
.
.
};

我需要像访问它一样

myJSON.tmp[0].a = 10;
myJSON.tmp2[0][1].c2_str = "hello world"

任何意见都受到高度赞赏

Javascript属性不像在C中那样类型化,因此javascript中没有纯粹的"等效"表达式。 您不会像 C 代码那样预先声明类型化数据结构。 我在javascript中给定的变量或属性可以分配任何值或引用 - 没有硬类型。 因此,如果没有像 C 那样只能包含特定类型的变量,就没有像 C 那样预先声明数据结构定义。

相反,您只需声明要在活动对象上使用的属性,或者如果您打算使用其中的许多属性,则可以创建一个原型,您可以在需要时实例化该原型。

活动对象实例的直接声明有点像最后一个结构,如下所示:

var my = {
    number: 10,
    tmp: new Array(100),
    tmp2: new Array(100)
};

这将声明一个名为 my 的对象,该对象具有三个属性,分别是 numbertmptmp2number最初包含数字10,其他两个属性包含长度为 100 的数组,其值undefined 。 我不知道有什么紧凑的方法可以在 javascript 中预定义您的二维数组,而无需在循环中运行代码来初始化它。

此数据定义将允许您访问my.numbermy.tmp等。

如果希望数组包含具有属性本身的对象,则需要使用对象填充这些数组。

var my = {
    number: 10,
    tmp: [{a: 1, c_str: "foo"}, {a: 2, c_str: "whatever"}],
    tmp2: new Array(100)
};

或者,在代码中,您可以使用如下代码将 item 添加到 tmp 数组中:

var my = {
    number: 10,
    tmp: [],
    tmp2: []
};
my.tmp.push({a: 1, c_str: "foo"});
my.tmp.push({a: 2, c_str: "whatever"});

或者,您可以单独创建对象,然后将其放入数组中:

var obj = {};        // new empty object
obj.a = 1;           // assign property
obj.c_str = "foo";   // assign property
my.tmp.push(obj);    // put object into the array
obj = {};            // new empty bject
obj.a = 2;
obj.c_str = "whatever";
my.tmp.push(obj);

或者,您可以像这样单独分配每个属性:

my.tmp.push({});           // put empty object into the array
my.tmp[0].a = 1;           // assign property to the object
my.tmp[0].c_str = "foo";   // assign property to the object
my.tmp.push({});
my.tmp[1].a = 2;
my.tmp[1].c_str = "whatever";

无论哪种情况,您都可以像这样访问数据:

console.log(my.tmp[0].a);       // 1
console.log(my.tmp[0].c_str);   // "foo"