在数组json中使用对象时C程序不起作用

时间:2019-11-25 09:18:21

标签: c json object

在下面的代码中,如果我尝试在不存在位置的情况下访问压力值,则该代码运行正常。但是,如果包含位置密钥,则它会显示分段错误(核心转储)错误。任何帮助将不胜感激。预先感谢。

以下是json格式的数据和c语言的代码 代码:

Json文件

 {
   "location": [
      {
          "location_type": "GPS",
          "lat": 19.123456,
          "lng": 72.123456,
          "ttf": 12
      },
      {
          "location_type": "WIFI",
          "wifiAccessPoints": [
              {
                  "macAddress": "AB:12:AC:13:AD:14",
                  "signalStrength": 0
              }
          ]
      }
    ],

"pressure": [
      30.02,
      30.29,
      29.13,
      28.99,
      28.43,
      27.11,
      27.99,
      27.46,
      26.11,
      26.04,
      25.27,
      24.55,
      24.35,
      23.87,
      22.76
    ]
}

C代码:

#include "json-c/json.h"

void main(){
    FILE *fp;
    char buffer[1024];
    struct json_object *parsed_json;

    struct json_object *imei;
    struct json_object *age;
    struct json_object *friends;
    struct json_object *friend;
    size_t n_friends;

    size_t i;   

    fp = fopen("json_trial2.json","r");
    fread(buffer, 1024, 1, fp);
    fclose(fp);

    parsed_json = json_tokener_parse(buffer);

    json_object_object_get_ex(parsed_json, "pressure", &friends);

     n_friends = json_object_array_length(friends);
     printf("Found %lu friends\n",n_friends);

     for(i=0;i<n_friends;i++) {`enter code here`
        friend = json_object_array_get_idx(friends, i);
        printf("%lu. %s\n",i+1,json_object_get_string(friend));
    }
return; 
}

0 个答案:

没有答案