Home > OS >  Write sequence of character not as string as value in dictionary
Write sequence of character not as string as value in dictionary

Time:11-22

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

CodePudding user response:

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'),
}

CodePudding user response:

That is the definition of the JSON Spec

A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.


Note that in python code that is same, a string is enclosed in simple or double quotes


Without the quotes, it would be impossible to parse it, no quotes means a numerical value. If you try to parse and print it, you'll see no problem

import json

x = {'k1': 'v1', 'k2': 10}
print(x)  # {'k1': 'v1', 'k2': 10}
x = json.dumps(x)
print(x)  # {"k1": "v1", "k2": 10}
x = json.loads(x)
print(x)  # {'k1': 'v1', 'k2': 1O}
  • Related