I have an interesting problem.
I am creating a dictionary in a for loop which I finally want to save a .js file. I need this file for another task in javascript. I want to dynamically add the elements of the list as keys to the dictionary. As values I want to compose a function, which is not saved as string within the dictionary. I must not be saved as a string, otherwise javascript is not able to interpret it as a function.
import json
someList = ["a", "b", "c", "d"]
newDict = {}
for letter in someList:
newDict[letter] = f"require('some/path/{letter}')"
with open("newFile.json", "w") as file:
file.write(json.dumps(newDict))
When I now have a look at the .json file, I get this
{
"a": "require('some/path/a')",
"b": "require('some/path/b')",
"c": "require('some/path/c')",
"d": "require('some/path/d')",
}
However, what I need is this (no quotation marks around the value of the key
{
"a": require('some/path/a'),
"b": require('some/path/b'),
"c": require('some/path/c'),
"d": require('some/path/d'),
}
Is there a way to achieve this? I am not sure if json.dumps() is the proper function here. However, JavaScript Objects and JSON have a lot in common: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
>Solution :
Try this:
someList = ["a", "b", "c", "d"]
newDict = "{\n"
for letter in someList:
newDict += f'\t"{letter}": require(\'some/path/{letter}\'),\n'
newDict += "}"
with open("newFile.json", "w") as file:
file.write(newDict)
This is what you will get in the .json file
{
"a": require('some/path/a'),
"b": require('some/path/b'),
"c": require('some/path/c'),
"d": require('some/path/d'),
}