I have a existing .json file in GitHub similar to below.
{
"quiz": {
"sport": {
"q1": {
"question": "Which one is correct team name in NBA?",
"options": [
"New York Bulls",
"Los Angeles Kings",
"Golden State Warriros",
"Huston Rocket"
],
"answer": "Huston Rocket"
}
},
"maths": {
"q1": {
"question": "5 + 7 = ?",
"options": [
"10",
"11",
"12",
"13"
],
"answer": "12"
},
"q2": {
"question": "12 - 8 = ?",
"options": [
"1",
"2",
"3",
"4"
],
"answer": "4"
}
}
}
}
I want to add new key and value to "maths" using Powershell. I tried below commands after cloned the git repo into my local directory
$FilePath = 'C:Userstest.json
$y = Get-Content $FilePath | ConvertFrom-Json
$value = @`
{
"question": "12 - 6 = ?",
"options": [
"1",
"2",
"3",
"6"
],
"answer": "6"
}
`@
$resultObject = $value | ConvertFrom-Json
$y.quiz.maths | Add-Member -MemberType NoteProperty -Name "q3" -Value $resultObject
$y | ConvertTo-Json -Depth 3 | Set-Content -Path $FilePath
Then committed and pushed the changes. When I checked the comparasion between ‘main’ branch and my ‘feature’ branch, entire file has been rewritten because of new whitespaces.
Note:
- "-compress" command did not help here
- If I merge and again raise a PR with new values, It gives that specific commit only but this will continue unwanted whitespaces
Questions;
1. Is there any proper way to do this without having unwanted whitespaces
2. Can we do it without converting into PowerShell object. I know we can convert it to a’String’ using ‘-Raw’ option, then how do we add above new property and make single commit which having only specific change
3. Is there any other way add new value to this .json file using PowerShell except above 2 options?
2
Answers
We can simply update the Powershell version to 7+ and use -Depth option when converting to PowerShell object and use same Depth option when converting back to the JSON file. This way, it fixed the issue
This seems like a good place to use a Class that defines the structure of your "questions", it would allow to more easily add new ones to your Json file.
First step is to define the Class:
Now that is done you can reuse it (create new questions) this way:
And lastly, you can add this new question to your Json like this:
Resulting Json from this example would be: