How to find your way through the inside of Glamorous Toolkit: printing a Json to a file
A newcomer to Glamorous Toolkit got stuck when trying to write a JSON to a file. The discussion on our Discord got to the point in which the programmer got to the following snippet which was not quite working in the desired way, and then asked how could the environment support the discovery process.
The snippet looked something like this:
'sample.json' asFileReference writeStreamDo: [:aStream | dictionary asJson printOn: aStream ]
The challenge was how to print the JSON object. The programmer already found
asJson but simply sending it a
printOn: did not seem to work. So, let's start from that
asJson and see where we get.
The first thing we do is to ask for references to it. We can do that by searching for references from the UI (pressing Primary+n), or with a script:
We see there are 4 senders of this message. The last one is quite intriguing as it is annotated with
<gtExample>. So, what is an example? It's a method that returns an object (with or without assertions). Interestingly, the editor offers a couple of buttons, including an inspect button:
Inspecting the result of the example, we get a
GtJsonBasic subclass: #GtJson
instance. The inspector shows several views. One of them seems quite similar to our current interest: JSON String.
Oh, it prints the JSON string. Nice. But how is it implemented? We press Alt+click on the name of the view to see the source code of the view:
So, what do we see there? A text editor view. And right there we see how the
text: is implemented:
STONJSON toStringPretty: self jsonObject
So, let's try it. We open the playground from the inspector and try it:
What do you know! We get our string. Now, let's put it together and add this string to the file in the same playground:
'somefile.txt' asFileReference writeStreamDo: [ :s | s nextPutAll: (STONJSON toStringPretty: self jsonObject) ]; yourself
it works! Now, we move to the left and create the script that works without state:
'somefile.txt' asFileReference writeStreamDo: [ :s | s nextPutAll: (STONJSON toStringPretty: GtJsonExamples new simplePersonJsonObject asJson jsonObject) ]; yourself
Nice, but there is one more thing to do. Let's extract the object in a separate variable:
And we're done.
This is a nice example of how to leverage the environment for exploring and learning the environment. All answers were found casually and were available in the system.