I want to modify the current JSON file with the following change:
I want to edit the "Vs" column and split that data into two columns. I want it to be split into two columns named team 1 and team 2 respectively by splitting data after 'vs'.
How should I do that using python script?
Input: JSON data (this is sample data.)
[
{
"Match No": "1",
"Date": "17-10-21",
"Vs": "Sri Lanka vs Ireland",
"Rounds": "1st",
"Group": "Group A"
},
Required Output: JSON data
[
{
"Match No": "1",
"Date": "17-10-21",
"Team1": "Sri Lanka",
"Team2": "Ireland",
"Rounds": "1st",
"Group": "Group A"
},
CodePudding user response:
So, I used the library json to serialize your input. THen you only need to loop over each object in the json array and create a new json object from the data. I hope you understand the principal.
import json
input = """
[
{
"Match No": "1",
"Date": "17-10-21",
"Vs": "Sri Lanka vs Ireland",
"Rounds": "1st",
"Group": "Group A"
}
]
"""
result = json.loads("""
[
]
""")
for o in json.loads(input):
teams = o["Vs"].split(" vs ")
result.append({
"Match No": o["Match No"],
"Date": o["Date"],
"Team 1": teams[0],
"Team 2": teams[1],
"Rounds": o["Rounds"],
"Group": o["Group"]
})
print(result)