skip to Main Content

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:

  1. "-compress" command did not help here
  2. 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


  1. Chosen as BEST ANSWER

    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


  2. 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:

    class Question {
        [string] $question
        [string[]] $options
        [string] $answer
    
        Question([string] $question) {
            $this.question = $question
        }
    
        [Question] AddOptions([scriptblock] $options) {
            $this.options = $options.Invoke()
            return $this
        }
    
        [Question] AddAnswer([string] $answer) {
            $this.answer = $answer
            return $this
        }
    
        [psnoteproperty] ToNoteProperty([string] $name) {
            return [psnoteproperty]::new($name, $this)
        }
    }
    

    Now that is done you can reuse it (create new questions) this way:

    $newQuestion = [Question]::new('12 - 6 = ?').
        AddOptions{ 1, 2, 3, 6 }.
        AddAnswer(6).
        ToNoteProperty('q3')
    

    And lastly, you can add this new question to your Json like this:

    $json = Get-Content pathtojsonfile.json -Raw | ConvertFrom-Json
    # `.quiz.maths` is the variable path here, the rest would remain the same
    $json.quiz.maths.PSObject.Properties.Add($newQuestion)
    $json | ConvertTo-Json -Depth 4 | Set-Content pathtojsonfile.json
    

    Resulting Json from this example would be:

    {
      "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"
          },
          "q3": {
            "question": "12 - 6 = ?",
            "options": [
              "1",
              "2",
              "3",
              "6"
            ],
            "answer": "6"
          }
        }
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search