c - 将JSON文件中的数据提取到c中的结构
问题描述
此代码旨在从 JSON 文件中提取数据:
[{ "name": "alice", "age": 30, "friends" : ["marc","max" ,"alice"] },
{"name": "john", "age": 25,"friends" : ["fr","mario" ,"Jim"]}]
并将数据存储到一个结构中,所以这是代码:
static int c ;
typedef struct {
char name[25] ;
int age ;
char *amis ;
} personne ;
static personne * PerArray;
static size_t n_objects;
static int n_friends ;
void ShowInfo ( int n_friends);
int main(int argc, char **argv) {
FILE *fp;
char buffer[1024];
struct json_object *parsed_json;
struct json_object *name;
struct json_object *age;
struct json_object *friends;
struct json_object *friend;
size_t n_friends;
struct json_object *parsed_json_1;
static size_t n_objects;
size_t j;
size_t i;
fp = fp = fopen("file.json","r");
if ( fp == NULL)
{
printf("UNable to open file\n");
exit(EXIT_FAILURE);
}
fread(buffer, 1024, 1, fp);
fclose(fp);
parsed_json = json_tokener_parse(buffer);
n_objects = json_object_array_length(parsed_json);
PerArray = (personne *) malloc (n_objects* sizeof(personne)) ;
for(i=0;i<2;i++)
{
parsed_json_1 = json_object_array_get_idx(parsed_json,i);
json_object_object_get_ex(parsed_json_1, "name", &name);
json_object_object_get_ex(parsed_json_1, "age", &age);
json_object_object_get_ex(parsed_json_1, "friends", &friends);
strcpy(PerArray[i].name ,json_object_get_string(name));
printf("Name: %s\n", PerArray[i].name);
PerArray[i].age = json_object_get_int(age) ;
printf("Age: %d\n", PerArray[i].age);
n_friends = json_object_array_length(friends);
printf("Found %lu friends\n",n_friends);
PerArray[i].amis = malloc(sizeof(char) * n_friends);
for(j=0 ; j< n_friends ; j++)
{
friend = json_object_array_get_idx(friends, j);
printf("%zu. %s\n",j+1,json_object_get_string(friend));
strcpy(PerArray[i].amis[j] ,json_object_get_string(friend));
printf("%zu. %s\n",j+1,PerArray[i].amis[j]);
}
}
}
我有分段错误的错误,通常故障在这一行:
strcpy(PerArray[i].amis[j] ,json_object_get_string(friend));
我只是通过使用 strcpy 将字符串朋友放入结构中。
任何人都可以帮忙吗?
解决方案
这是错误的,PerArray[i].amis[j]
没有任何意义。
strcpy(PerArray[i].amis[j], json_object_get_string(friend));
你可能想要这个:
typedef struct {
char name[25] ;
int age ;
char **amis ; // two stars here, you need a pointer to a pointer to char
} personne ;
...
PerArray[i].amis = malloc(sizeof(char**) * n_friends);
// now PerArray[i].amis points to an array of n_friends pointers to char*
...
const char *pfriend = json_object_get_string(friend);
PerArray[i].amis[j] = malloc(strlen(pfriend) + 1);
strcpy(PerArray[i].amis[j], pfriend);
不过可能还有其他问题。
推荐阅读
- python - 带有身份验证访问令牌的 python 请求
- c# - 将 UINT64 编码为浮点数
- java - 你能给我这个由我制作的新选择排序算法的时间近似值吗(如 n^2 , n*2 , nlogn )
- javascript - Angular - 在本地文本文件中保存 blob?
- operating-system - 无需驱动程序直接寻址外部硬件?
- windows - 我应该编写什么类型的驱动程序来模拟鼠标输入,就好像它是由真实设备发出的一样?
- php - 大于 5MB 的附件的 GMail API“请求实体太大错误 413”
- c - 在 if/else 中使用几乎相同的语句减少 C 程序中的代码重复?
- sql - 在 SQL 中两列之间的模糊匹配中创建真/假列
- c++ - 让 Windows 10 讲述人说出一些文字