PowerShell JSON формат добавления значений - PullRequest
0 голосов
/ 13 июня 2018

Я добавляю данные в файл json.Я делаю это по

$blockcvalue =@" 
    {
    "connectionString":"server=(localdb)\\mssqllocaldb; Integrated Security=true;Database=$database;"
    }
"@

$ConfigJson = Get-Content C:\Users\user\Desktop\myJsonFile.json -raw | ConvertFrom-Json

$ConfigJson.data | add-member -Name "database" -value (Convertfrom-Json $blockcvalue) -MemberType NoteProperty

$ConfigJson | ConvertTo-Json| Set-Content C:\Users\user\Desktop\myJsonFile.json

Но формат получается так:

{
    "data":  {
                    "database":  {
                                 "connectionString":  "server=(localdb)\\mssqllocaldb; Integrated Security=true;Database=mydatabase;"
                             }
                }
}

но мне нужно вот так:

{
    "data": {
    "database":"server=(localdb)\\mssqllocaldb; Integrated Security=true;Database=mydatabase;"
    }
    }
}

Может кто-нибудь помочь, пожалуйста

Ответы [ 3 ]

0 голосов
/ 13 июня 2018

Вот моя функция для предварительного вывода вывода JSON:

function Format-Json {
    <#
    .SYNOPSIS
        Prettifies JSON output.
    .DESCRIPTION
        Reformats a JSON string so the output looks better than what ConvertTo-Json outputs.
    .PARAMETER Json
        Required: [string] The JSON text to prettify.
    .PARAMETER Indentation
        Optional: The number of spaces to use for indentation. Defaults to 2.
    .PARAMETER AsArray
        Optional: If set, the output will be in the form of a string array, otherwise a single string is output.
    .EXAMPLE
        $json | ConvertTo-Json  | Format-Json -Indentation 4
    #>
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
        [string]$Json,

        [int]$Indentation = 2,
        [switch]$AsArray
    )
    # If the input JSON text has been created with ConvertTo-Json -Compress
    # then we first need to reconvert it without compression
    if ($Json -notmatch '\r?\n') {
        $Json = ($Json | ConvertFrom-Json) | ConvertTo-Json -Depth 100
    }

    $indent = 0
    $Indentation = [Math]::Abs($Indentation)
    $regexUnlessQuoted = '(?=([^"]*"[^"]*")*[^"]*$)'

    $result = $Json -split '\r?\n' |
        ForEach-Object {
            # If the line contains a ] or } character, 
            # we need to decrement the indentation level unless it is inside quotes.
            if ($_ -match "[}\]]$regexUnlessQuoted") {
                $indent = [Math]::Max($indent - $Indentation, 0)
            }

            # Replace all colon-space combinations by ": " unless it is inside quotes.
            $line = (' ' * $indent) + ($_.TrimStart() -replace ":\s+$regexUnlessQuoted", ': ')

            # If the line contains a [ or { character, 
            # we need to increment the indentation level unless it is inside quotes.
            if ($_ -match "[\{\[]$regexUnlessQuoted") {
                $indent += $Indentation
            }

            $line
        }

    if ($AsArray) { return $result }
    return $result -Join [Environment]::NewLine
}

Используйте это так:

$ConfigJson | ConvertTo-Json | Format-Json | Set-Content C:\Users\user\Desktop\myJsonFile.json
0 голосов
/ 02 августа 2019

Заменить

(Convertfrom-Json $blockcvalue)

на

(Convertfrom-Json $blockcvalue).connectionString

Тогда свойство data.database вашего выходного объекта будет напрямую содержать значение "server=(localdb)\\...", если необходимо, а нечерез вложенный объект со свойством connectionString.

0 голосов
/ 13 июня 2018

Добавьте Format-Json, который сделает это за вас.

$ConfigJson | ConvertTo-Json | Format-Json | Set-Content C:\Users\user\Desktop\myJsonFile.json

Помните, что Format-Json должен быть выполнен до set-content.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...