Header for libjson-glib

Headers, Bindings, Libraries for use with FreeBASIC, Please include example of use to help ensure they are tested and usable.
Post Reply
TJF
Posts: 3809
Joined: Dec 06, 2009 22:27
Location: N47°, E15°
Contact:

Header for libjson-glib

Post by TJF »

Image

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

JSON is built on two structures:
  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangeable with programming languages also be based on these structures.

JSON-GLib combines the JSON features with GLib-Object. You can generate a JSON stream directly from an GLib object and vice versa.

Download (version 0.14.2):
Testcode:

Code: Select all

#INCLUDE "json-glib.bi"

g_type_init()

'' create parser
VAR pars = json_parser_new()

'' create pointer for error messages (if any)
DIM AS GError PTR errr

'' some input to test (whitespaces should get removed in output)
VAR t = "{""name"":[[[1,2,3,4],5,    6],7,            8]}"
'var t = "[{""hello"":""hello""}]" 
'var t = "[{""hello"":1},{ ""foo"":""what_foo""}] " 

'' parse the stream (+ output error if any)
?json_parser_load_from_data(pars, t, LEN(t), @errr)
IF errr THEN ?*errr->message

'' get the root node
VAR node = json_parser_get_root(pars)

'' create generator, set root
VAR gen = json_generator_new()
json_generator_set_root(gen, node)

'' generate output (should be equal to input)
?*json_generator_to_data(gen, 0)

'' free memory
g_object_unref(gen)
g_object_unref(pars)
badidea
Posts: 2594
Joined: May 24, 2007 22:10
Location: The Netherlands

Re: Header for libjson-glib

Post by badidea »

7 years have passed. No replies. I wonder why, some possibilities:
(a) The library so obvious and easy to use that no questions are needed
(b) No one cares about JSON
(c) It looks way too complex

Case (c) seems most likely to me. I tried to figure out how to work with this. There are 2 APIs: low and high level. The low level API deals with a lot of Gnome and C stuff which I don't understand yet. The high level API is a bit easier. Examples below are my translation attempts (with some modifications) from the C-code example on the project page: https://wiki.gnome.org/Projects/JsonGlib

--- Example 1 - Read and parse a JSON file ---
From file into a tree data structure, nothing more.
Add "," or "{" to the file to test it with incorrect input.

Code: Select all

#include "json-glib.bi"

function parseFile(fileName as string) as integer
	dim as JsonParser ptr pParser
	dim as JsonNode ptr pRoot
	dim as GError ptr pError = 0

	pParser = json_parser_new()

	json_parser_load_from_file(pParser, fileName, @pError)
	if pError then
		print "Unable to parse " & fileName & ":"
		print *pError->message
		g_error_free(pError)
		g_object_unref(pParser)
		return -1 'fail
	end if

	pRoot = json_parser_get_root(pParser)

	'* manipulate the object tree and then exit *'

	g_object_unref(pParser)

	return 0 'ok
end function

if parseFile("colors.json")  = 0 then
	print "Parse result: Success"
else
	print "Parse result: Failure"
end if

print "Press any key to exit" 
getkey() 'wait for key

Uses this file (colors.json):

Code: Select all

{
  "colors": [
    {
      "color": "black",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,255,255,1],
        "hex": "#000"
      }
    },
    {
      "color": "white",
      "category": "value",
      "code": {
        "rgba": [0,0,0,1],
        "hex": "#FFF"
      }
    },
    {
      "color": "red",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,0,0,1],
        "hex": "#FF0"
      }
    },
    {
      "color": "blue",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [0,0,255,1],
        "hex": "#00F"
      }
    },
    {
      "color": "yellow",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,255,0,1],
        "hex": "#FF0"
      }
    },
    {
      "color": "green",
      "category": "hue",
      "type": "secondary",
      "code": {
        "rgba": [0,255,0,1],
        "hex": "#0F0"
      }
    }
  ]
}
Last edited by badidea on May 05, 2020 13:49, edited 2 times in total.
badidea
Posts: 2594
Joined: May 24, 2007 22:10
Location: The Netherlands

Re: Header for libjson-glib

Post by badidea »

--- Example 2 - Build and read a JSON tree ---
Using the higher level API

Code: Select all

#include "json-glib.bi"

'JsonBuilder: a simple API for building JSON trees

dim as JsonBuilder ptr pBuilder = json_builder_new()

json_builder_begin_object(pBuilder)

 json_builder_set_member_name(pBuilder, "url")
 json_builder_add_string_value(pBuilder, "http://www.gnome.org/img/flash/two-thirty.png")

 json_builder_set_member_name(pBuilder, "size")
 json_builder_begin_array(pBuilder)
  json_builder_add_int_value(pBuilder, 652)
  json_builder_add_int_value(pBuilder, 242)
 json_builder_end_array(pBuilder)

json_builder_end_object(pBuilder)

dim as JsonGenerator ptr pGen = json_generator_new()
dim as JsonNode ptr pRoot = json_builder_get_root(pBuilder)
json_generator_set_root(pGen, pRoot)
dim as gchar ptr pStr = json_generator_to_data(pGen, 0)

g_object_unref(pGen)
g_object_unref(pBuilder)

print """str"" now contains the string:"
print *pStr

'JsonReader: a cursor-based API for parsing JSON trees 

dim as JsonParser ptr pParser = json_parser_new()
json_parser_load_from_data(pParser, pStr, -1, 0)

dim as JsonReader ptr pReader = json_reader_new(json_parser_get_root(pParser))

json_reader_read_member(pReader, "url")
 dim as const zstring ptr pUrl = json_reader_get_string_value(pReader)
json_reader_end_member(pReader)

json_reader_read_member(pReader, "size")
 json_reader_read_element(pReader, 0)
 dim as integer w = json_reader_get_int_value(pReader)
 json_reader_end_element(pReader)
 json_reader_read_element(pReader, 1)
 dim as integer h = json_reader_get_int_value(pReader)
 json_reader_end_element(pReader)
json_reader_end_member(pReader)

print "Data form reader:"
print "Url: " & *pUrl
print "Size: "  & w & " x "  & h

g_object_unref(pReader)
g_object_unref(pParser)

json_node_free(pRoot)

print "Press any key to exit" 
getkey()
badidea
Posts: 2594
Joined: May 24, 2007 22:10
Location: The Netherlands

Re: Header for libjson-glib

Post by badidea »

--- Example 3 - Deserialization (low level) ---
NOT working yet. Confusing stuff like: FOO_TYPE_OBJECT, GObject, G_TYPE_OBJECT.
See 2nd example on: https://wiki.gnome.org/Projects/JsonGlib

Code: Select all

#include "json-glib.bi"

'#define FOO_TYPE_OBJECT (foo_object_get_type())

'* usual GObject boilerplate *'

enum FooBlahEnum
	FOO_BLAH_ALPHA
	FOO_BLAH_BRAVO
	FOO_BLAH_CHARLIE
end enum

static as const zstring ptr pFoo_object_json = _
@"{ ""bar"" : 42, ""baz"" : true, ""blah"" : ""bravo"" }"

print *pFoo_object_json

'dim as FooObject ptr pFoo
dim as GObject ptr pFoo
dim as GError ptr pError = 0

dim as gint bar_int
dim as gboolean baz_boolean
dim as FooBlahEnum blah_enum

'pFoo = json_construct_gobject(FOO_TYPE_OBJECT, pFoo_object_json, -1, @pError)
'pFoo = json_construct_gobject(G_TYPE_OBJECT, pFoo_object_json, -1, @pError)
pFoo = json_construct_gobject(g_object_get_type(), pFoo_object_json, -1, @pError)

if pError then
	print "Unable to create instance: " & *pError->message
else
	'* FooObject has three properties: bar, blah and baz *'
	'g_object_get(G_OBJECT(pFoo), "bar", @bar_int, "baz", @baz_boolean, "blah", @blah_enum, 0)
	g_object_get(pFoo, "bar", @bar_int, "baz", @baz_boolean, "blah", @blah_enum, 0)

	print "bar_int: " & bar_int
	print "baz_boolean: " & baz_boolean
	print "blah_enum: " & blah_enum

	g_object_unref(pFoo)
end if

print "Press any key to exit" 
getkey()
xiaoyao
Posts: 121
Joined: May 05, 2020 2:01

Re: Header for libjson-glib

Post by xiaoyao »

i use json by vb6,use "sctiptctronl","javascript",it can't use
MsgBox Js.Eval("JSON.stringify(JsonObj)")
need addcode : json3.min-ansi.js
can you test the cpu speed for :stringify
(get the json string)
libjson-glib vs ScriptControl

Code: Select all

Dim htm As String
htm = "var JsonObj= {'name':'Kasun', 'address':'columbo','age': '29'}"
 Dim Js As New ScriptControl
Js.Language = "Javascript"
Js.AddCode htm
MsgBox Js.Eval("JsonObj.address")
xiaoyao
Posts: 121
Joined: May 05, 2020 2:01

Re: Header for libjson-glib

Post by xiaoyao »

badidea wrote:--- Example 3 - Deserialization (low level) ---
NOT working yet. Confusing stuff like: FOO_TYPE_OBJECT, GObject, G_TYPE_OBJECT.
See 2nd example on: https://wiki.gnome.org/Projects/JsonGlib

Code: Select all

#include "json-glib.bi"

'#define FOO_TYPE_OBJECT (foo_object_get_type())

Many libraries have complicated methods of use. I really hope there is a way to reduce the learning cost. I am creating a code base, and code standardization is also necessary
xiaoyao
Posts: 121
Joined: May 05, 2020 2:01

Re: Header for libjson-glib

Post by xiaoyao »

what about run speed about "libjson-glib"
pk:
vb6- json to string (stringify)
You can try different methods, which one runs faster, such as VBJSON.CLS, JSON.JS, JSON2.JS, JSON3.JS
my test: Json1.js is quick then json3.js
Json1.js,usedtime:1.059312 (ms)
Json2.js,usedtime:1.114954 (ms)
Json3.js,usedtime:4.310751 (ms)
vbjson,usedtime:6.26(ms)
viewtopic.php?f=7&t=28525&start=15#p271865
Post Reply