哈希表ConvertTo-Json PowerShell格式问题
问题描述:
我在PowerShell中使用哈希表来获取数据并将其转换为JSON。我是PS新手,因此无法验证JSON。这里是我的代码:哈希表ConvertTo-Json PowerShell格式问题
################## intro
$userIntro = @{}
function getIntro {
$userIntro.Add("first_name", "John")
$userIntro.Add("last_name", "Smith")
$userIntro.Add("age", "28")
}
getIntro
$userIntro | ConvertTo-Json
################## address
$address = @{}
function getAddress {
$address.Add("street", "21 2nd St")
$address.Add("city", "New York")
$address.Add("state", "NY")
$address.Add("zipcode", 12345)
}
getAddress
$address | ConvertTo-Json
出把代码是这样的:
{
"last_name": "Smith",
"age": "28",
"first_name": "John"
}
{
"street": "21 2nd St",
"state": "NY",
"zipcode": 12345,
"city": "New York"
}
正如你所看到的,这不是有效的JSON语法,因为我将两个不同的对象和它的相应的输出。
但是,我真正想要实现的是以下内容......如何将对象合并为一个转换?并最好添加分解到这样的水平。
{
"userIntro": {
"last_name": "Smith",
"age": "28",
"first_name": "John"
},
"address": {
"street": "21 2nd St",
"state": "NY",
"zipcode": 12345,
"city": "New York"
}
}
答
我想你只需要结合$address
和$userIntro
,然后将其转换成JSON哈希表:
################## intro
$userIntro = @{}
function getIntro {
$userIntro.Add("first_name", "John")
$userIntro.Add("last_name", "Smith")
$userIntro.Add("age", "28")
}
getIntro
#$userIntro | ConvertTo-Json
################## address
$address = @{}
function getAddress {
$address.Add("street", "21 2nd St")
$address.Add("city", "New York")
$address.Add("state", "NY")
$address.Add("zipcode", 12345)
}
getAddress
#$address | ConvertTo-Json
$combined = @{}
$combined.Add("userIntro", $userIntro)
$combined.Add("address", $address)
$combined | ConvertTo-Json
输出:
{
"address": {
"zipcode": 12345,
"street": "21 2nd St",
"city": "New York",
"state": "NY"
},
"userIntro": {
"last_name": "Smith",
"first_name": "John",
"age": "28"
}
}
正是我一直在寻找。谢谢@Scott Heaberlin – Omar