json_funcs.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. struct json_object *oj = NULL;
  39. int ret;
  40. if (fixup_get_svalue(msg, (gparam_p)json, &json_s) != 0) {
  41. LM_ERR("cannot get json string value\n");
  42. return -1;
  43. }
  44. if (fixup_get_svalue(msg, (gparam_p)field, &field_s) != 0) {
  45. LM_ERR("cannot get field string value\n");
  46. return -1;
  47. }
  48. dst_pv = (pv_spec_t *)dst;
  49. j = json_tokener_parse(json_s.s);
  50. if (is_error(j)) {
  51. LM_ERR("empty or invalid JSON\n");
  52. if(j!=NULL) json_object_put(j);
  53. return -1;
  54. }
  55. json_object_object_get_ex(j, field_s.s, &oj);
  56. if(oj!=NULL) {
  57. value = (char*)json_object_to_json_string(oj);
  58. dst_val.rs.s = value;
  59. dst_val.rs.len = strlen(value);
  60. dst_val.flags = PV_VAL_STR;
  61. dst_pv->setf(msg, &dst_pv->pvp, (int)EQ_T, &dst_val);
  62. ret = 1;
  63. } else {
  64. ret = -1;
  65. }
  66. if(j!=NULL) json_object_put(j);
  67. return ret;
  68. }