此代码旨在从 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 将字符串朋友放入结构中。
任何人都可以帮忙吗?