Skip to content

Scrapy, a fast high-level web crawling & scraping framework for Python.

Make Settings.getlist() parse JSON lists (#8416)

Kishan Mehta00ca2a9c07ba
diff --git a/scrapy/settings/__init__.py b/scrapy/settings/__init__.py
index b52ec429a..f1b2cdca3 100644
--- a/scrapy/settings/__init__.py
+++ b/scrapy/settings/__init__.py
@@ -225,11 +225,13 @@ class BaseSettings(MutableMapping[str, Any]):
def getlist(self, name: str, default: list[Any] | None = None) -> list[Any]:
"""
Get a setting value as a list. If the setting original type is a list,
- a copy of it will be returned. If it's a string it will be split by
- ",". If it is an empty string, an empty list will be returned.
+ a copy of it will be returned. If it's a string it will be evaluated as
+ a JSON list, or split by "," as a fallback. If it is an empty string,
+ an empty list will be returned.
For example, settings populated through environment variables set to
- ``'one,two'`` will return a list ['one', 'two'] when using this method.
+ ``'one,two'`` or ``'["one", "two"]'`` will return a list ['one', 'two']
+ when using this method.
:param name: the setting name
:type name: str
@@ -241,7 +243,11 @@ class BaseSettings(MutableMapping[str, Any]):
if not value:
return []
if isinstance(value, str):
- value = value.split(",")
+ try:
+ value_loaded = json.loads(value)
+ except ValueError:
+ value_loaded = None
+ value = value_loaded if isinstance(value_loaded, list) else value.split(",")
return list(value)
def getdict(
diff --git a/tests/test_settings/__init__.py b/tests/test_settings/__init__.py
index e94078591..4736e1df2 100644
--- a/tests/test_settings/__init__.py
+++ b/tests/test_settings/__init__.py
@@ -547,6 +547,23 @@ class TestBaseSettings:
msg = caplog.records[0].message
assert "tests.test_settings.Component1" in msg
+ @pytest.mark.parametrize(
+ ("value", "expected"),
+ [
+ ('["one", "two"]', ["one", "two"]),
+ ('["a,b", "c"]', ["a,b", "c"]),
+ ("[500, 502]", [500, 502]),
+ ("[]", []),
+ ("one,two", ["one", "two"]),
+ ('{"a": 1}', ['{"a": 1}']),
+ ("123", ["123"]),
+ ("[one,two", ["[one", "two"]),
+ ],
+ )
+ def test_getlist_str(self, value, expected):
+ settings = BaseSettings({"S": value})
+ assert settings.getlist("S") == expected
+
def test_getdictorlist(self):
settings = BaseSettings()