Home > Software design >  Reformat JSON file in Python by consolidating text?
Reformat JSON file in Python by consolidating text?

Time:06-07

I have a JSON file of the following format:

[
{"url": "example1.com", "date": "Jan 1", "text": ["Here is some ", "example 1 text"]},
{"url": "example2.com", "date": "Jan 2", "text": ["Here is some ", "example 2 text"]},
]

Which I upload into Python using:

with open("data.json") as data:
    data = json.load(data)

I would like to reformat the uploaded data so that the text is consolidated and not enclosed by brackets, as such:

[
{"url": "example1.com", "date": "Jan 1", "text": "Here is some example 1 text"},
{"url": "example2.com", "date": "Jan 2", "text": "Here is some example 2 text"},
]

CodePudding user response:

You can format the "text" field as follows:

with open("data.json") as data:
    data = json.load(data)
    for website in data:
        website["text"] = ' '.join(website["text"])
  • Related