I have a bunch of separate .json files in one folder. Like this:
P50_00001.json
P50_00002.json
P50_00003.json
P50_00004.json
P50_00005.json....
Lots of them.
If you open them - they all look like this:
{
"Participant_id": "P50_00001",
"no_of_people": "Single",
"apparent_gender": "M",
"geographic_location": "JPN",
"ethnicity": "Japanese",
"capture_device_used": "iOS14",
"camera_orientation": "Portrait",
"camera_position": "Frontal View",
"Indoors_Outdoors_env": "Outdoors",
"lighting_condition": "Medium",
"Occluded": "None",
"scene_category": "Nature",
"camera_movement": "Still",
"action": "No action",
"Indoors_Outdoors_in_moving_car_or_train": "Outdoors",
"daytime_nighttime": "daytime"
}
But I need them to have square brackets in the beginning and the end:
[
{
"Participant_id": "P50_00001",
"no_of_people": "Single",
"apparent_gender": "M",
"geographic_location": "JPN",
"ethnicity": "Japanese",
"capture_device_used": "iOS14",
"camera_orientation": "Portrait",
"camera_position": "Frontal View",
"Indoors_Outdoors_env": "Outdoors",
"lighting_condition": "Medium",
"Occluded": "None",
"scene_category": "Nature",
"camera_movement": "Still",
"action": "No action",
"Indoors_Outdoors_in_moving_car_or_train": "Outdoors",
"daytime_nighttime": "daytime"
}
]
How can I batch-add square brackets to all the .json files in one directory at once? Any way possible - powershell, javascript, python or even some sort of notepad, that's why I tag all of it.
Thanks!
CodePudding user response:
You can do this by using PowerShell:
$files = Get-ChildItem | Where Name -Like "*.json"
foreach ($file in $files) {
$value = Get-Content $file | ConvertFrom-Json
$value = ,@($value)
$value | ConvertTo-Json | Set-Content $file
}
Note the comma before the @($value)
. This is needed to get PowerShell to add a superfluous layer of list. Otherwise, single-item lists are dissolved into their item immediately.
CodePudding user response:
import json
file_dir = ['P50_00001.json', 'P50_00002.json', 'P50_00003.json', 'P50_00004.json', 'P50_00005.json'] # TODO: Change it!
x = []
for i in file_dir:
file = open(i)
obj = json.load(file)
x.append(obj)
with open("new_req_file.json", "w") as file:
json.dump(x, file)
I first created the list with all of the dir for your json files. Then I looped over every dir to open and load the json data into python dict. Then I appended the that dict into a list.
After looping that list holds every dict from json files. And finally I just dumped the list into new json file!