Cannot convert dictionary into a string

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By markb37373


I have the contents of a dictionary below that I want converted into a string.

var dictionary_as_string = JSON.parse("{9:[\"Berry\", 6]}") 

if typeof(dictionary_as_string.result) == TYPE_DICTIONARY: 
	print("not dictionary")
print("result; ",dictionary_as_string.result)

However, dictionary_as_string.result returns null and doesn’t convert into a string. It also prints “not dictionary”. If I change the dictionary contents from "{9:[\"Berry\", 6]}" as used above to "{\"Berry\": 6}", it is converted into a string successfully. Why is this and how can I convert the contents to a string?

aren’t JSONS a strings in the end ?
just str(result)
if You can print something to console, You can also stror var2str it succesfully

Inces | 2022-09-21 05:47

I’ve tried it, it still prints null both times. If you try to make a variable with a null value a string, it still will be null. I don’t know how to solve this?

markb37373 | 2022-09-21 13:50

no man. It is a string, that says “null”.
That clearly means, Your dictionary contains null. Result of parsing is null. JSON is invalid.

Inces | 2022-09-21 16:49

:bust_in_silhouette: Reply From: jgodfrey

As documented at JSON, the key in a JSON object must be a string.

So, when parsing that string as JSON, you can’t have that integer key. If you print error_string after the call to JSON.parse (as below), you’ll see a meaningful error…

(Also, note that I’ve cleaned up the string creation syntax a bit…)

var dictionary_as_string = JSON.parse('{9:["Berry", 6]}')

To fix it, you’ll need to make that key a string, like:

var dictionary_as_string = JSON.parse('{"9":["Berry", 6]}')
if typeof(dictionary_as_string.result) == TYPE_DICTIONARY:
	print("not dictionary")

That should result in the following output: