1 /**
2 * Copyright (C) 2013 Flowroute LLC (flowroute.com)
3 *
4 * This file is part of Kamailio, a free SIP server.
5 *
6 * This file is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version
10 *
11 *
12 * This file is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 *
21 */
22
23 #define _GNU_SOURCE
24 #include <stdio.h>
25 #include <jansson.h>
26 #include <limits.h>
27
28 #include "../../core/lvalue.h"
29
30 #include "jansson_utils.h"
31
jansson_to_val(pv_value_t * val,char ** freeme,json_t * v)32 int jansson_to_val(pv_value_t* val, char** freeme, json_t* v) {
33
34 val->flags = 0;
35
36 if(json_is_object(v) || json_is_array(v)) {
37 const char* value = json_dumps(v, JSON_COMPACT|JSON_PRESERVE_ORDER);
38 *freeme = (char*)value;
39 val->rs.s = (char*)value;
40 val->rs.len = strlen(value);
41 val->flags = PV_VAL_STR;
42 }else if(json_is_string(v)) {
43 const char* value = json_string_value(v);
44 val->rs.s = (char*)value;
45 val->rs.len = strlen(value);
46 val->flags = PV_VAL_STR;
47 }else if(json_is_boolean(v)) {
48 val->ri = json_is_true(v) ? 1 : 0;
49 val->flags = PV_TYPE_INT|PV_VAL_INT;
50 }else if(json_is_real(v)) {
51 char* value = NULL;
52 if(asprintf(&value, "%.15g", json_real_value(v))<0) {
53 ERR("asprintf failed\n");
54 return -1;
55 }
56 *freeme = value;
57 val->rs.s = value;
58 val->rs.len = strlen(value);
59 val->flags = PV_VAL_STR;
60 }else if(json_is_integer(v)) {
61 long long value = json_integer_value(v);
62 if ((value > INT_MAX) || (value < INT_MIN)) {
63 char* svalue = NULL;
64 if (asprintf(&svalue, "%"JSON_INTEGER_FORMAT, value) < 0) {
65 ERR("asprintf failed\n");
66 return -1;
67 }
68 *freeme = svalue;
69 val->rs.s = svalue;
70 val->rs.len = strlen(svalue);
71 val->flags = PV_VAL_STR;
72 } else {
73 val->ri = (int)value;
74 val->flags = PV_TYPE_INT|PV_VAL_INT;
75 }
76 }else if(json_is_null(v)) {
77 val->flags = PV_VAL_NULL;
78 }else {
79 ERR("unrecognized json type: %d\n", json_typeof(v));
80 return -1;
81 }
82 return 0;
83 }
84