json_funcs.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /**
  2. * $Id$
  3. *
  4. * Copyright (C) 2011 Flowroute LLC (flowroute.com)
  5. *
  6. * This file is part of Kamailio, a free SIP server.
  7. *
  8. * This file is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 2 of the License, or
  11. * (at your option) any later version
  12. *
  13. *
  14. * This file is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License
  20. * along with this program; if not, write to the Free Software
  21. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  22. *
  23. */
  24. #include <stdio.h>
  25. #include <string.h>
  26. #include <json.h>
  27. #include "../../mod_fix.h"
  28. #include "../../lvalue.h"
  29. #include "json_funcs.h"
  30. int json_get_field(struct sip_msg* msg, char* json, char* field, char* dst)
  31. {
  32. str json_s;
  33. str field_s;
  34. pv_spec_t *dst_pv;
  35. pv_value_t dst_val;
  36. char *value;
  37. struct json_object *j = NULL;
  38. if (fixup_get_svalue(msg, (gparam_p)json, &json_s) != 0) {
  39. LM_ERR("cannot get json string value\n");
  40. return -1;
  41. }
  42. if (fixup_get_svalue(msg, (gparam_p)field, &field_s) != 0) {
  43. LM_ERR("cannot get field string value\n");
  44. return -1;
  45. }
  46. dst_pv = (pv_spec_t *)dst;
  47. j = json_tokener_parse(json_s.s);
  48. if (is_error(j)) {
  49. LM_ERR("empty or invalid JSON\n");
  50. if(j!=NULL) json_object_put(j);
  51. return -1;
  52. }
  53. value = (char*)json_object_to_json_string(json_object_object_get(j, field_s.s));
  54. dst_val.rs.s = value;
  55. dst_val.rs.len = strlen(value);
  56. dst_val.flags = PV_VAL_STR;
  57. dst_pv->setf(msg, &dst_pv->pvp, (int)EQ_T, &dst_val);
  58. if(j!=NULL) json_object_put(j);
  59. return 1;
  60. }