我在PowerShell中使用Hash Tables来获取数据,而不是将其转换为JSON。我是PS新手,因此坚持验证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
代码的输出是这样的:
{
"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"
}
}
答案 0 :(得分:3)
我认为您只需要一个结合了$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"
}
}