Write multiple lists to JSON Python

Hi everyone,

I have a python file that scrapes a website which creates multiple lists of data.

I would like to be able to save the scraped data, I figure the best way would be JSON.

What are the best methods to go from: question_list = ['question 1', 'question 2', 'question_3'] answer_list = ['a', 'b', 'c'], ['a','b','c'], ['cat', 'dog',' rabbit']

To a valid JSON format for later retrieval?

Apologies for the beginner question ;)Read More


If the question and answer lists are directly related to each other, I'd put them together in a dictionary instead of separate lists. That would also be easier to translate into json.

Btw, in case you don't know about it yet... https://docs.python.org/3/library/json.html3Reply


Notice that for this line - answer_list = ['a', 'b', 'c'], ['a','b','c'], ['cat', 'dog',' rabbit']

I actually didn't even know that was valid Python. It actually evaluates to: >>> answer_list (['a', 'b', 'c'], ['a', 'b', 'c'], ['cat', 'dog', ' rabbit'])

The () (instead of [] or {} for instance) indicates a tuple, which is like a list except it's immutable on the data type level.

Anyway, what's the best way to JSON-serialize it? Try: >>> import json >>> json.dumps(answer_list) '[["a", "b", "c"], ["a", "b", "c"], ["cat", "dog", " rabbit"]]'

"how make it a json file" >>> with open("example.json", "w") as outfile: ...     outfile.write(json.dumps(answer_list)) ... 61 1Reply


The () (instead of [] or {} for instance) indicates a tuple

Akshually, a comma , indicates a tuple :)1Reply1 more reply


In Python's response, I mean.


Oh. Hah, yeah, you're right. Tuples tripped me up when I first started learning ,because of how the output formats them. thus felt the need to comment.

Video liên quan