简体   繁体   中英

How to write a list of string as double quotes, so that json can load?

Consider the following code, where the json can't load back because after the manipulation, the single quotes become double quotes, how can write to file as double quote list so that json can load back?

import configparser
import json

config = configparser.ConfigParser()
config.read("config.ini")
l = json.loads(config.get('Basic', 'simple_list'))

new_config = configparser.ConfigParser()
new_config.add_section("Basic")
new_config.set('Basic', 'simple_list', str(l))

with open("config1.ini", 'w') as f:
    new_config.write(f)

config = configparser.ConfigParser()
config.read("config1.ini")
l = json.loads(config.get('Basic', 'simple_list'))

The settings.ini file content is like this:

[Basic]
simple_list = ["a", "b"]

As already mentionned by @L3viathan, the purely technical answer is "use json.dumps() instead of str()" (and yes, it works for dicts too).

BUT: storing json in an ini file is very bad idea. "ini" is a file format on it's own (even if not as strictly specified as json or yaml) and it has been designed to be user-editable with just any text editor. FWIW, the simple canonical way to store "lists" in an ini file is simply to store them as comma separated values, ie:

[Basic]
simple_list = a,b

and parse this back when reading the config as

values = config.get('Basic', 'simple_list')).split(",")

wrt/ "storing dicts", an ini file IS already a (kind of) dict since it's based on key:value pairs. It's restricted to two levels (sections and keys), but here again that's by design - it's a format designed for end-users, not for programmers.

Now if the ini forma doesn't suits your needs, nothing prevents you from just using a json (or yaml) file instead for the whole config

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM