[Pharo-users] How to write out simple Json?

Tim Mackinnon tim at testit.works
Thu Feb 28 08:36:22 EST 2019


Hi Sven - is there no convenience shortcut we can use in our code to make this less wordy when we are specifying it?

E.g. the following is very convenient to write - but doesn’t work (as you have $‘ and not $“ )

ex := { 'track'-> 'pharo'. 
	'language' -> 'smalltalk'.
	 'exercises' ->
		{'slug' -> 'hello'.
		'id' -> 55.
		'topics' -> #('a' 'b' 'c') }
		}.
		
String streamContents: [ :stream |
	(STONWriter on: (stream)) prettyPrint: true; 	writeList: ex ].

I had thought maybe NeoJSON might help and put:

String streamContents: [ :stream |
	(NeoJSONWriter on: (stream)) prettyPrint: true;
	"mapInstVarsFor: Association;"
	nextPut: ex ].

But I get the error about missing an association mapping. If I uncomment that bit - I get things like: { "value" : “pharo" },

So is there a way I can write a simple mapper for Association that will write out the key in a string and the value in a string?

I’m quite suprised we can’t easily write out fragments of Json in our code in a light weight way? Or do I need to make a proper Config object and then teach it how to map properly such that rather than fiddling with our { x->y } dictionary sugar I do something like:

  Config new at: ‘id’ is: 123; at: ‘name’ is: ‘Tim’; at: ‘exercises’ is: #(1 2 3).

And I guess at:is: can do the Association asDictionary thing?

But I thought Neo might give me something like that, as it must be terribly common?

Tim

> On 28 Feb 2019, at 13:16, Sven Van Caekenberghe <sven at stfx.eu> wrote:
> 
> STONJSON toString: { #id->1. #name->'tim' } asDictionary.
> 
> JSON cannot deal with Associations by themselves.
> 
>> On 28 Feb 2019, at 14:05, Tim Mackinnon <tim at testit.works> wrote:
>> 
>> I am stumped about how to write out some simple json (for a config file). I didn't think I need Neo, and STONJSON would be fine but it seems like creating items like: 
>> 
>> { 'id'-> self id. 'name' -> self name }
>> 
>> gives an error about the association. I think you have to do: { ('id'-> self id) asDictionary. ('name' -> self name) asDictionary } everywhere….
>> 
>> But when I switch over to NeoJsonWriter it also complains about Assocations too. I just want a simple output like:
>> { "id" : 12, "name" : "tim” }
>> 
>> I thought it was simple to do this? Am I missing something obvious.
>> 
>> Tim
> 
> 




More information about the Pharo-users mailing list