简体   繁体   中英

How to copy latest Json data from another Json file PowerShell?

I have a source.Json file like below

{
  "kind": "sql#backupRunsList",
  "items": [
    {
      "kind": "sql#backupRun",
      "status": "SUCCESSFUL",
      "enqueuedTime": "2023-01-11T00:33:21.903Z",
      "id": "1673391600000",
      "startTime": "2023-01-11T00:33:21.949Z",
      "endTime": "2023-01-11T00:38:47.459Z",
      "type": "AUTOMATED",
      "windowStartTime": "2023-01-10T23:00:00Z",
      "instance": "instance",
      "selfLink": "https://sqladmin.googleapis.com/v1/projects/project/instances/instance/backupRuns/1673391600000",
      "location": "us",
      "backupKind": "SNAPSHOT"
    },
    {
      "kind": "sql#backupRun",
      "status": "SUCCESSFUL",
      "enqueuedTime": "2023-01-09T23:36:39.776Z",
      "id": "1673305200000",
      "startTime": "2023-01-09T23:36:39.826Z",
      "endTime": "2023-01-09T23:42:05.542Z",
      "type": "AUTOMATED",
      "windowStartTime": "2023-01-09T23:00:00Z",
      "instance": "instance ",
      "selfLink": "https://sqladmin.googleapis.com/v1/projects/project/instances/instance/backupRuns/1673305200000",
      "location": "us",
      "backupKind": "SNAPSHOT"
    },

And I have a target.json file below

{
  "restoreBackupContext":
  {
    "backupRunId": 123456,
    "project": "project",
    "instanceId": "instance"
  }
}

How to copy the data "id": "1673391600000", from source.json to "backupRunId": value to target.json

In target backupRunId value "123456" should be replace to "1673391600000" value using power shell.

getting id value from source file, How to copy to target file

$content=Get-Content -Path source.json
$JsonData=$content | ConvertFrom-Json
$JsonData.Items.id[0]

Please any one suggest

If you only want to process the first item in $JsonData.Items and update the single target json file

# Grab json text from source file and convert to PSobjects
$source = Get-Content .\source.json | ConvertFrom-Json

# Grab json text from target file and convert to PSobjects
$target = Get-Content .\target.json | ConvertFrom-Json

# Update $target object with id from $source object
$target.restoreBackupContext.backupRunId = $source.items[0].id

# Take updated $target object, convert back to json and save back to target.json file
$target | ConvertTo-Json | Set-Content -Path .\target.json

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM