Dictionary returned from String.parseJSONFile gives only nil!

I have used the String.parseJSONFile method, which returns an Array of Dicts. But when I ask for keys (Dict['mykey']) I only get nils although the key-value pairs exist (asking keys() and values() methods confirm this).
Why is this happening?

TL;DR Dict["myKey"]

IIRC a dictionary read from JSON reads keys as strings, so the keys should be enclosed in double quotes. (Single quotes denote symbols; double quotes denote strings. When the delimiters are omitted in the post window, they look the same, but they aren’t interchangeable.)

hjh

The in built json is terribly broken - I’d avoid it.

1 Like

If you have any other ideas, I’d love to hear them.

Use one of the quarks that does this. It is a known issue, the problem is just how much of user code will be broken when fixing it - or if we should deprecate the old one.

1 Like
1 Like

Thanks!

I think JSONlib.parseFile is the corresponding one, but this also uses the built-in String.parseJSONFile:

*parseFile {|filePath, customDecoder=nil, useEvent=true, postWarnings=true|
		^this.new(
			postWarnings,
			customDecoder: customDecoder,
			useEvent: useEvent,
		).prConvertToSC(filePath.parseJSONFile)
	}

You should read the readme GitHub - musikinformatik/JSONlib: A JSON de- and encoder for SuperCollider · GitHub which gives the following example

// use Symbol instead of String to get rid of escaping quotation marks
j = '{"hello": 42}';

// turn this into an Event
d = JSONlib.convertToSC(j);
// -> ( 'hello': 42 )

// an integer gets parsed as an integer
d[\hello].class
// -> Integer

// compare to the built-in method of sclang
// it uses a Dictionary instead of an Event
d = j.parseJSON()
// -> Dictionary[ (hello -> 42) ]

// but 42 is a string here
d["hello"].class
// -> String

Being one of the authors, I also consider this quark rather hacky. At some point it would be great to fix this upstream, but this involves a bit more caution and thought b/c of sclang dictionary semantics and backwards compatibility.

This Quark hasn’t its own JSON parser (though this would be still somehow feasible to do within sclang IMO) but rather tries to check if the entries are numbers/booleans/nil etc

1 Like

This is good, indeed! Thanks!