Heroku is convenient, isn't it? If you just move it for the time being, even a beginner can do it. This is a story I was addicted to when I tried to run Discord bot on Heroku with Heroku.
Python's json.loads ()
is a function that converts a dictionary type (associative array) converted into a character string by json.dumps ()
etc. to the original dictionary type.
Naturally, the return value is a dictionary type.
I was able to use it on local and GCP without any problem, but when I moved it on heroku in the same way, string type was returned for some reason. It's not a punch line that you accidentally used json.dumps ()
.
Heroku
##Json string.Unzip with loads
loaded_dict = json.loads(dumped_string)
##Output like that even if you print
print(loaded_dict)
# {"key1":"value1", "key2":{"v2k1":"v2v1"}}
##But it's a string
print(loaded_dict["key1"])
# TypeError: string indices must be integers
for k, v in loaded_dict.items():
...
# AttributeError: 'str' object has no attribute 'items'
print(type(loaded_dict["key1"]))
# <class 'str'>
Heroku's search obstruction was so strong that I hit only articles like "I tried using Heroku" and couldn't find the root cause of the problem.
However, the display of print (loaded_dict)
itself was not strange, so I solved it with eval ()
.
Heroku
##Bite eval
loaded_dict = eval(json.loads(dumped_string))
##Solution!
print(loaded_dict["key1"])
# "value1"
Recommended Posts