1 /* json-utils.c - JSON utility API
2  *
3  * This file is part of JSON-GLib
4  * Copyright 2015  Emmanuele Bassi
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library. If not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 /**
21  * SECTION:json-utils
22  * @Title: Utility API
23  * @Short_description: Various utility functions
24  *
25  * Various utility functions.
26  */
27 
28 #include "config.h"
29 
30 #include "json-utils.h"
31 #include "json-parser.h"
32 #include "json-generator.h"
33 
34 /**
35  * json_from_string:
36  * @str: a valid UTF-8 string containing JSON data
37  * @error: return location for a #GError
38  *
39  * Parses the string in @str and returns a #JsonNode representing
40  * the JSON tree. If @str is empty, this function will return %NULL.
41  *
42  * In case of parsing error, this function returns %NULL and sets
43  * @error appropriately.
44  *
45  * Returns: (transfer full) (nullable): a #JsonNode, or %NULL
46  *
47  * Since: 1.2
48  */
49 JsonNode *
json_from_string(const char * str,GError ** error)50 json_from_string (const char  *str,
51                   GError     **error)
52 {
53   JsonParser *parser;
54   JsonNode *retval;
55 
56   g_return_val_if_fail (str != NULL, NULL);
57 
58   parser = json_parser_new ();
59   if (!json_parser_load_from_data (parser, str, -1, error))
60     {
61       g_object_unref (parser);
62       return NULL;
63     }
64 
65   retval = json_parser_steal_root (parser);
66 
67   g_object_unref (parser);
68 
69   return retval;
70 }
71 
72 /**
73  * json_to_string:
74  * @node: a #JsonNode
75  * @pretty: whether the output should be prettyfied for printing
76  *
77  * Generates a stringified JSON representation of the contents of
78  * the passed @node.
79  *
80  * Returns: (transfer full): the string representation of the #JsonNode
81  *
82  * Since: 1.2
83  */
84 char *
json_to_string(JsonNode * node,gboolean pretty)85 json_to_string (JsonNode *node,
86                 gboolean  pretty)
87 {
88   JsonGenerator *generator;
89   char *retval;
90 
91   g_return_val_if_fail (node != NULL, NULL);
92 
93   generator = json_generator_new ();
94   json_generator_set_pretty (generator, pretty);
95   json_generator_set_root (generator, node);
96 
97   retval = json_generator_to_data (generator, NULL);
98 
99   g_object_unref (generator);
100 
101   return retval;
102 }
103