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

Tim Mackinnon tim at testit.works
Thu Feb 28 16:35:20 EST 2019

Sven- thinking a bit more

> On 28 Feb 2019, at 13:59, Sven Van Caekenberghe <sven at stfx.eu <mailto:sven at stfx.eu>> wrote:
> This is wrong !!
> Think about it, what would then happen with a mixed list ?
> { #key->#value. 1. true }
> That would generate invalid JSON.

I actually went and tried my little hack with your example and it gives the same error as STONWriter - so actually my proposal isn’t so horrid as inferred… (but still not as knowledgable as everyone else on this for sure).

As a reminder - I wanted a compact way to express the following (sort of like you would expect in Javascript) -

ex := { 
	'track'-> 'pharo'. 
	'language' -> 'smalltalk'.
	'exercises' -> {
		'slug' -> 'hello'.
		'id' -> 55.
		'topics' -> #('a' 'b' 'c') } 

String streamContents: [ :stream |
	(STONJSONWriter on: stream) jsonMode: true; prettyPrint: true; nextPut: ex  ].

My pragmatic changes were 2 methods as follows -

writeAssociation: association
		encodeKey: association key 
		value: association value

writeObject: anObject do: block
	jsonMode ifTrue: [ 
		(anObject isKindOf: OrderedCollection)
			“so you don’t have to asArray everywhere"
			ifTrue: [ ^self writeList: anObject ].
		(anObject isKindOf: OrderedDictionary)
			“so you can output { } for libs that need it - does require asOrderedDictionary"
			ifTrue: [ ^self writeMap: anObject ]].
	super writeObject: anObject do: block 

(And if you assume your using json - a class method

 on: writeStream
	^ (super on: writeStream)
			jsonMode: true;
			prettyPrint: true;

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.pharo.org/pipermail/pharo-users_lists.pharo.org/attachments/20190228/dc7ff0aa/attachment.html>

More information about the Pharo-users mailing list