2016-12-05 1 views
1

JSON 파일을 단일 값으로 업데이트하려고합니다. 파일이 업데이트되었지만 원하지 않거나 필요없는 추가 데이터가 업데이트되었습니다.PowerShell로 JSON 파일 업데이트

{ 
    "name": "perf-a", 
    "cft_file":"cft/cft.json", 
    "parameters": { 
    "AppEnvironmentType": "perf", 
    "Image": "16963e76" 
    }, 
    "tags": { 
    "Owner": "[email protected]", 
    "CostCenter": "12345" 
    } 
} 
"16963e76"여기
$outPath = "C:\Program Files (x86)\Go Agent\pipelines\mypipeline\Application\Application\Id.txt" 
$imageid = Get-Content $outPath 
$filejson = Get-Content -Raw -Path $file.FullName -Encoding UTF8 | ConvertFrom-Json 
$filejson.parameters.Image = $imageid 
$filejson | ConvertTo-Json | Out-File $filepath -Encoding utf8 -Force 

내가 내 JSON의 모습을 기대하는 것입니다

Id.txt 한 문자열을 포함 : 여기

은 PowerShell 스크립트에서 미리보기입니다

다음은 JSON이 실제로 업데이트 된 모습입니다.

{ 
    "name": "perf-a", 
    "cft_file": "cft/cft.json", 
    "parameters": { 
     "AppEnvironmentType": "perf", 
     "Image": { 
      "value": "16963e76", 
      "PSPath": "C:\\Program Files (x86)\\Go Agent\\pipelines\\mypipeline\\Application\\Application\\Id.txt", 
      "PSParentPath": "C:\\Program Files (x86)\\Go Agent\\pipelines\\mypipeline\\Application\\Application", 
      "PSChildName": "Id.txt", 
      "PSDrive": "C", 
      "PSProvider": "Microsoft.PowerShell.Core\\FileSystem", 
      "ReadCount": 1 
     } 
    }, 
    "tags": { 
     "Owner": "[email protected]", 
     "CostCenter": "12345" 
    } 
} 

이 문제의 원인은 무엇이며 어떻게 멈추게합니까?

감사합니다,

론다

+1

id.txt에서 문자열을 가져올 때 그렇습니다. powershell이 ​​환경에서 여러 개의 noteproperties를 추가하는 경우 대개 중요하지 않으므로 무시할 수 있습니다. 그러나 ConvertTo-JSON은 개체에서 이러한 노트 속성을 추출하여 json에 삽입합니다. tostring 메서드를 사용하면 내 솔루션은 문자열을 다른 문자열로 변경하지만 이번에는 노트 속성이 없으므로 작동합니다. –

답변

0

은 아마이 변경 :

`$filejson.parameters.Image = $imageid.value` 

당신이 $filejson.parameters.Image에 개체를 전달하기 때문에,하지만 당신은 해당 개체의 한 속성을해야합니다.

+1

이 해결책은 작동하지 않습니다. –

+0

'$ imageid'는 (단행 입력 파일에 적용된'Get-Content'의 출력이 할당 되었기 때문에)'[string]'인스턴스이므로, '.value' 속성 (Jim의 대답이 설명하는 것처럼 PS에서 추가 한 노트 속성으로 장식되어 있음). – mklement0

+0

P.: 질문에서 JSON 출력의'value' 속성은'ConvertTo-Json'이'NoteProperty' 및/또는'ScriptProperty' 멤버로 꾸며진 값 유형과 문자열을 어떻게 문자열 화하는지에 대한 결과물입니다. – mklement0

1

편집

는 솔루션 작업에 대한 정확한 이유를 덧붙였다.

id.txt에서 문자열을 가져올 때 powershell이 ​​환경에서 여러 개의 noteproperties를 추가하는 경우 대개 중요하지 않으므로 무시할 수 있습니다.

그러나 ConvertTo-JSON은 개체에서 이러한 메모 속성을 추출하여 json에 삽입하고 있습니다. tostring 메서드를 사용하여 내 솔루션은 문자열을 다른 문자열로 변경하지만 이번에는 노트 속성이 없으므로 작동합니다.

$outPath = "C:\Program Files (x86)\Go Agent\pipelines\mypipeline\Application\Application\Id.txt" 
$imageid = (Get-Content $outPath)ToString() 
$filejson = Get-Content -Raw -Path $file.FullName -Encoding UTF8 | ConvertFrom-Json 
$filejson.parameters.Image = $imageid 
$filejson | ConvertTo-Json | Out-File $filepath -Encoding utf8 -Force 

PREVIOUS INCORRECT 이유 :

은 $ imageid 실제로 당신이 그런 식으로 그것을 가져오고를 ConvertTo-JSON이 파일에 전체 개체를 가하고 객체입니다.

당신은 $ imageid가 단지 문자열이고, 아래처럼 tostring 메서드를 사용할 수있는 몇 가지 방법이 있는지 확인해야합니다.