I have Json data like this
{
"Library": [
{
"LibraryName": "John's Library",
"Books": [
{
"BookId": "0000786",
"BookName": "BookA",
}
]
}
]
}
I need to add one more book item to this json file via powershell to get an end result like
{
"Library": [
{
"LibraryName": "John's Library",
"Books": [
{
"BookId": "0000786",
"BookName": "BookA",
},
{
"BookId": "0000788",
"BookName": "BookB",
}
]
}
]
}
I tried the following snippet , but doesn't seem to add
$libraryFileContent = Get-Content $libraryFile
$libraryData = $ser.DeserializeObject($libraryFileContent)
$bookObject = (New-Object PSObject |
Add-Member -PassThru NoteProperty BookId '0000787' |
Add-Member -PassThru NoteProperty BookName 'BookB'
)
$libraryData.Library[0].Books | Add-Member (ConvertTo-JSON $bookObject)
Is there any easy way of doing this?
This is one of those where you think it should be a lot more complicated than it is! Try this -
$json = @"
{
"Library": [
{
"LibraryName": "John's Library",
"Books": [
{
"BookId": "0000786",
"BookName": "BookA"
}
]
}
]
}
"@
$x = $json | ConvertFrom-Json
$books = [PSCustomObject]@{"BookId" = "000788"; "Bookname" = "bookB"}
$x.Library[0].Books += $books
$x | ConvertTo-Json -Depth 4
Which should give -
{
"Library": [
{
"LibraryName": "John's Library",
"Books": [
{
"BookId": "0000786",
"BookName": "BookA"
},
{
"BookId": "000788",
"Bookname": "bookB"
}
]
}
]
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.