Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Write sequence of character not as string as value in dictionary

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
    "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'),
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading