Dump and restore JSON data strings

From Cuis CookBook
Jump to navigation Jump to search

Since Javascript is the only language running inside Web browsers it has become extremely popular to dump and exchange data in JSON format. How do I read a JSON dump made from others? How do I make my own?

First of all, to work with JSON you must load this package.

Feature require: 'JSON'.

Problem. I want to convert a Cuis data structure in JSON, how do i do it?

Solution. By example.

js1 := Json render: { 
  Dictionary newFromPairs: {'codice'. '111.653.735'. 'quantita'. '1'}. 
  Dictionary newFromPairs: {'codice'. '111.653.735'. 'quantita'. '2'} 
}. 

js1 print. "=>"
'[{"quantita": "1", "codice": "111.653.735"}, 
  {"quantita": "2", "codice": "111.653.735"}]'

Problem. I want to read some JSON string and use it as a data structure in Cuis, how do I do ?

Solution. By example. Using the output of previous problem.

jo1 := Json readFrom: (ReadStream on: js1). 

jo1 class.         "=> Array " 

(jo1 at: 1) class. "=> JsonObject " 

jo1 at: 1.         "=> a JsonObject('quantita'->'1' 'codice'->'111.653.735' ) " 

(jo1 at: 1) at: 'codice'. "=> '111.653.735' "

Dr. Nicola Mingotti. Last updated 03-Sep-2021. Tested in Cuis-5.0-4815.image .