Как получить значения json после json_tokener_parse()?

У меня есть следующий код

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>

#include <json/json.h>

int main(int argc, char **argv)
{
      json_object *new_obj;
      char buf[] = "{ \"foo\": \"bar\", \"foo2\": \"bar2\", \"foo3\": \"bar3\" }"
      new_obj = json_tokener_parse(buf);
      printf("The value of foo is %s" /*What I have to put here?*/);
      printf("The value of foo2 is %s" /*What I have to put here?*/);
      printf("The value of foo3 is %s" /*What I have to put here?*/);
      json_object_put(new_obj);
}

Я знаю, что мы должны использовать json_tokener_parse() разобрать строки json, но тогда я не знаю, как извлечь значения из json_object new_obj как указано в комментариях в коде выше

Как получить значения JSON после json_tokener_parse()?

3 ответа

Решение

Сначала вам нужно получить json_object на конкретный узел:

json_object *obj_foo = json_object_object_get(new_obj, "foo");

... тогда вы можете использовать соответствующий метод получения для получения значения узла определенного типа:

char *foo_val = json_object_get_string(obj_foo2);

Короче говоря, вы можете сделать:

printf("The value of foo is %s", 
    json_object_get_string(json_object_object_get(new_obj, "foo"))
);

Очевидно, что лучше сделать это в несколько этапов, чтобы вы могли проверять наличие ошибок (в данном случае: нулевые указатели) и предотвращать неопределенное поведение и тому подобное.

Вы можете найти документацию по JSON C API здесь.

Принятый ответ показывает, как использовать json_object_object_get функция, которая сейчас устарела.

json_object_object_get_ex следует использовать вместо

const char *json = "{ \"Name\": \"xxxxx\", \"Id\": 101, \"Voting_eligible\": true }";
json_object *root_obj = json_tokener_parse(json);

json_object *tmp;
if (json_object_object_get_ex(root_obj, "Name", &tmp){
    // Key Name exists
    printf("Name: %s\n", json_object_get_string(tmp));
    // Name: xxxxx
}

Привет, пожалуйста, посмотрите этот образец (ПРОВЕРЕНО). скопировать и вставить в вашу IDE

#include <stdio.h>
#include <json/json.h>

int main()
{
  /*Declaring the json data's in json format*/
  char buf[] = "{ \"Name\": \"xxxxx\", \"Id\": 101, \"Voting_eligible\": true }";

  /*Declaring the Json_object.To pass the Json string to the newly created Json_object*/
  json_object *new_obj = json_tokener_parse(buf);

  /*To get the data's then we have to get to the specific node by using the below function*/

  json_object *obj_Name;//Declaring the object to get  store the value of the Name
  obj_Name = json_object_object_get(new_obj,"Name");//This in-built func used to traverse through specific node

  json_object *obj_Id;//Declaring the object to get  store the value of the  Id
  obj_Id = json_object_object_get(new_obj,"Id");//This in-built func used to traverse through specific node

  json_object *obj_Vote;//Declaring the object to get  store the value of the  Vote
  obj_Vote = json_object_object_get(new_obj,"Voting_eligible");//This in-built func used to traverse through specific node

  /* To store the values we use temp char */
  char *Name = json_object_get_string(obj_Name);// This is in-built func to get the string(value) from "json_object_object_get()"
  char *Id = json_object_get_string(obj_Id);
  char *Vote = json_object_get_string(obj_Vote);




  /* we can also use like this statement directly to reduce the pgm size */
  //  printf("Name : %s\n",json_object_get_string(json_object_object_get(new_obj, "Name")));
  //  printf("Id : %s\n",json_object_get_string(json_object_object_get(new_obj, "Id")));
  //  printf("Voting_eligible : %s\n",json_object_get_string(json_object_object_get(new_obj, "Voting_eligible")));

  printf("Name : %s\n",Name);
  printf("Id : %s\n",Id);
  printf("Voting_eligible : %s\n",Vote);

  json_object_put(new_obj);// to return the pointer to its originalobjects


}
Другие вопросы по тегам