This is how my input string ($inputStr) looks like:
{
"CloudId" : "67f8f457-1c4a-4622-a743-638318af04e3",
"ComputerName" : "Computer1",
"DeploymentErrorInfo" : {
"IsConditionallyTerminating" : null,
"MomAlertSeverity" : null,
"DisplayableErrorCode" : null,
"IsSuccess" : null,
"DetailedCode" : null,
"IsMomAlert" : null,
"DetailedSource" : null,
"CloudProblem" : null,
"IsTerminating" : null,
"DetailedErrorCode" : null,
"ExceptionDetails" : null,
"Code" : null,
"ShowDetailedError" : null,
"RecommendedActionCLI" : null,
"ErrorCodeString" : null,
"IsDeploymentBlocker" : null,
"ErrorType" : null,
"RecommendedAction" : null,
"Problem" : null,
"MessageParameters" : null
},
"GrantedToList" : [],
"ID" : "00000000-0000-0000-0000-000000000000",
"LocalAdminUserName" : "administrator",
"Name" : "Computer1",
"NewVirtualNetworkAdapterInput" : [],
"OperatingSystemInstance" : {
"Architecture" : null,
"Edition" : null,
"Description" : null,
"Version" : null,
"Name" : null,
"OSType" : null,
"ProductType" : null
},
"Owner" : {
"UserName" : null,
"RoleID" : null,
"RoleName" : null
},
"StampId" : "23e6799c-33d4-45ea-8e4f-49ec7d5f26e0",
"StartVM" : true,
"VMNetworkAssignments" : [],
"VMTemplateId" : "fdc73f71-1c6d-4e8f-9d02-21c7f4756c2d"
}
I am converting this to an object using ConvertFrom-Json command.
$paramObject = ConvertFrom-Json -InputObject $inputStr
I want it to print 'VM Computer1 is ready' but it does not work and it actually prints the whole string:
Write-Host "VM $paramObject.Name is ready" # prints the entire thing
Write-Host 'VM $paramObject.Name is ready' # prints command
Write-Host $paramObject.Name # prints VM Name so I know I am able to get the VM Name.
When using string interpolation, you need to use a sub-expression $(...) whenever you want to access a member of an object:
Write-Host "VM $($paramObject.Name) is ready"
Otherwise, PowerShell will treat the .Name part as just normal text.
Related
This is how my input string ($inputStr) looks like:
{
"CloudId" : "67f8f457-1c4a-4622-a743-638318af04e3",
"ComputerName" : "Computer1",
"DeploymentErrorInfo" : {
"IsConditionallyTerminating" : null,
"MomAlertSeverity" : null,
"DisplayableErrorCode" : null,
"IsSuccess" : null,
"DetailedCode" : null,
"IsMomAlert" : null,
"DetailedSource" : null,
"CloudProblem" : null,
"IsTerminating" : null,
"DetailedErrorCode" : null,
"ExceptionDetails" : null,
"Code" : null,
"ShowDetailedError" : null,
"RecommendedActionCLI" : null,
"ErrorCodeString" : null,
"IsDeploymentBlocker" : null,
"ErrorType" : null,
"RecommendedAction" : null,
"Problem" : null,
"MessageParameters" : null
},
"GrantedToList" : [],
"ID" : "00000000-0000-0000-0000-000000000000",
"LocalAdminUserName" : "administrator",
"Name" : "Computer1",
"NewVirtualNetworkAdapterInput" : [],
"OperatingSystemInstance" : {
"Architecture" : null,
"Edition" : null,
"Description" : null,
"Version" : null,
"Name" : null,
"OSType" : null,
"ProductType" : null
},
"Owner" : {
"UserName" : null,
"RoleID" : null,
"RoleName" : null
},
"StampId" : "23e6799c-33d4-45ea-8e4f-49ec7d5f26e0",
"StartVM" : true,
"VMNetworkAssignments" : [],
"VMTemplateId" : "fdc73f71-1c6d-4e8f-9d02-21c7f4756c2d"
}
I am converting this to an object using ConvertFrom-Json command.
$paramObject = ConvertFrom-Json -InputObject $inputStr
I want it to print 'VM Computer1 is ready' but it does not work and it actually prints the whole string:
Write-Host "VM $paramObject.Name is ready" # prints the entire thing
Write-Host 'VM $paramObject.Name is ready' # prints command
Write-Host $paramObject.Name # prints VM Name so I know I am able to get the VM Name.
When using string interpolation, you need to use a sub-expression $(...) whenever you want to access a member of an object:
Write-Host "VM $($paramObject.Name) is ready"
Otherwise, PowerShell will treat the .Name part as just normal text.
I've this type of data :
{
"cidr" : "X.X.X.X/27",
"defaultGateway" : "X.X.X.X",
"full" : false,
"id" : "X.X.X.X",
"ipAddressTab" : [
{
"alias_domain" : null,
"alias_name" : null,
"description" : "This is the network address for X.X.X.X/27",
"dnr_rr" : null,
"dns_domain" : null,
"environnement" : null,
"fdqn" : null,
"hostname" : null,
"ip" : "X.X.X.X",
"requester" : null,
"status" : "reserved",
"type" : "network"
},
{
"alias_domain" : null,
"alias_name" : null,
"description" : "This is the default gateway address for X.X.X.X/27",
"dnr_rr" : null,
"dns_domain" : null,
"environnement" : null,
"fdqn" : null,
"hostname" : null,
"ip" : "X.X.X.X",
"requester" : null,
"status" : "reserved",
"type" : "gateway"
},
{
"alias_domain" : "toto.com",
"alias_name" : "",
"description" : "this is a test",
"dns_domain" : "",
"environnement" : "test",
"fdqn" : "XXX",
"hostname" : "XXX",
"ip" : "X.X.X.X",
"requester" : "XXX",
"status" : "allocated",
"type" : "VM"
},
{
"alias_domain" : "toto.com",
"alias_name" : "",
"description" : "this is a test",
"dns_domain" : "",
"environnement" : "test",
"fdqn" : "XXX",
"hostname" : "XXX",
"ip" : "X.X.X.X",
"requester" : "XXX",
"status" : "allocated",
"type" : "VM"
},
{
"ip" : "X.X.X.X",
"status" : "reserved"
},
{
"ip" : "X.X.X.X",
"status" : "reserved"
},
{
"ip" : "X.X.X.X",
"status" : "reserved"
},
{
"ip" : "X.X.X.X",
"status" : "reserved"
},
{
"alias_domain" : null,
"alias_name" : null,
"description" : "This is the broadcast address for X.X.X.X/27",
"dnr_rr" : null,
"dns_domain" : null,
"environnement" : null,
"fdqn" : null,
"hostname" : null,
"ip" : "X.X.X.X",
"requester" : null,
"status" : "reserved",
"type" : "broadcast"
}
]
}
I want to extract the IPs with "reserved" as status but without extractig the data for the gateway/network/broadcast IPs :
cat myfile | jq '.ipAddressTab[] | select(.status == "reserved") | select(.type != "network") | select(.type != "gateway") | select(.type != "broadcast")'
The output is :
{
"ip": "X.X.X.X",
"status": "reserved"
}
{
"ip": "X.X.X.X",
"status": "reserved"
}
{
"ip": "X.X.X.X",
"status": "reserved"
}
{
"ip": "X.X.X.X",
"status": "reserved"
}
But where are the commas between each " IP part " ?
On my file, each part in Braces are separated by a comma :
{
"ip" : "X.X.X.X",
"status" : "reserved"
}, <=
{
"ip" : "X.X.X.X",
"status" : "reserved"
}, <=
{
"ip" : "X.X.X.X",
"status" : "reserved"
}, <=
{
"ip" : "X.X.X.X",
"status" : "reserved"
}, <=
There is a way to keep them when I parse my file with jq ?
Thanks !
JQ's input and output are streams of JSON entities. The items in those streams are not comma separated. Some JQ filters may emit more than one entity for each entity they read in. Some filters may not emit any entity for some of the entities that they read in.
In your case, your input is a stream of one object, and your output is a stream of multiple objects. This is because each single array input to the [] filter results in a stream of all of the items in the output. It sounds like you instead want your output to consist of one array of objects. Here are two broad ways to do it.
1. Use map instead of []
cat myfile | jq '.ipAddressTab | map(select(.status == "reserved") | select(.type != "network") | select(.type != "gateway") | select(.type != "broadcast"))'
The parameter to map is another filter. It will be applied to each item in the array, and all the entities emitted by that filter will be gathered into one new array.
2. Use [ ... ] to gather the results of a filter into an array
cat myfile | jq '.ipAddressTab | [ .[] | select(.status == "reserved") | select(.type != "network") | select(.type != "gateway") | select(.type != "broadcast") ]'
It might seem like putting values between square brackets is just creating an array with one entry, but in fact what this syntax means is to evaluate the filter between the brackets, take the entire stream of output from that filter and make an array out of it.
In fact, this is exactly how map is itself defined. But it's useful to know, because it lets you see how you might use [ ... ] in other ways to capture a sequence of values.
My very first question after using this site for my own learning! Still a beginner so go easy on me :)
I am trying to format JSON data within MSSQL Server. I have a static JSON file which I can get to display via OPENROWSET, and populate a variable. This JSON file has a "header" and then one or more "child" rows, basically an order header and order detail lines. I can successfully separately display the header's columns as a table in a result-set. I'd like to do the same with just the detail lines - the aim being to then store the header in a table and it's details in a table within SQL server - this part I'll have no issue with.
Here is some mock-up JSON data that I'm working with. This is the exact format I need to use, so I don't have any room to manoeuvre with it but I've populated it with test data:
{
"InputParameters" : {
"P_IN_ORDER_SOURCE" : "The_Web",
"P_IN_ORIG_SYS_DOCUMENT_REF" : "Order666",
"P_IN_SOLD_TO_CUST_NUMBER" : "JOEB11",
"P_IN_CUST_ORDER_NUMBER" : "JoeB5556667",
"P_IN_REQUEST_DATE" : "2021-01-20 08:10:06",
"P_IN_ORDER_ENTRY_DATE" : "2021-01-20 08:10:06",
"P_IN_SHIPTO_NAME" : "The Testing Co.",
"P_IN_SHIPTO_ADDR" : "82 Annweir Crescent",
"P_IN_SHIPTO_ADDR_2" : null,
"P_IN_SHIPTO_CITY" : "Atlantis",
"P_IN_SHIPTO_STATE" : "WSX",
"P_IN_SHIPTO_ZIP" : "AT55 666",
"P_IN_SHIPTO_COUNTRY" : "GB",
"P_IN_OPERATION_CODE" : "CREATE",
"P_IN_BOOKED_FLAG" : "N",
"P_IN_OU_NAME" : "ATL UK OU",
"P_IN_SPECIAL_INSTRUCTIONS" : null,
"P_IN_QUOTE_NUMBER" : null,
"P_IN_PRICELIST_ID" : "8",
"P_IN_EMAIL" : "testemail#testemail.com",
"P_IN_SHIPTO_COUNTY" : null,
"P_IN_SHIPPING_METHOD" : "Pre 930",
"P_IN_SHIPPING_INSTRUCTIONS" : null,
"P_IN_ATTENTION_TO" : "Joe Bloggs",
"P_IN_FREIGHT_CARRIER_CODE" : null,
"P_IN_IS_RETURN" : null,
"P_IN_SALES_REP" : null,
"P_IN_LINE_DATA" : [ {
"P_IN_LINE_DATA_ITEM" : [ {
"ORIG_SYS_DOCUMENT_REF" : "Order666",
"ORIG_SYS_LINE_REF" : "1",
"CUSTOMER_LINE_NUMBER" : "1",
"ITEM_TYPE_CODE" : "STANDARD",
"ITEM_DESCRIPTION" : "SKU7776",
"USER_ITEM_DESCRIPTION" : "SKU7776",
"TOP_MODEL_LINE_REF" : null,
"LINK_TO_LINE_REF" : null,
"COMPONENT_CODE" : null,
"ORDERED_QUANTITY" : "6",
"ORDER_QUANTITY_UOM" : null,
"UNIT_LIST_PRICE" : "16.95",
"UNIT_SELLING_PRICE" : "16.95",
"CALCULATE_PRICE_FLAG" : "N",
"OPERATION_CODE" : "INSERT"
}, {
"ORIG_SYS_DOCUMENT_REF" : "Order666",
"ORIG_SYS_LINE_REF" : "2",
"CUSTOMER_LINE_NUMBER" : "2",
"ITEM_TYPE_CODE" : "STANDARD",
"ITEM_DESCRIPTION" : "SKU12345",
"USER_ITEM_DESCRIPTION" : "SKU12345",
"TOP_MODEL_LINE_REF" : null,
"LINK_TO_LINE_REF" : null,
"COMPONENT_CODE" : null,
"ORDERED_QUANTITY" : "6",
"ORDER_QUANTITY_UOM" : null,
"UNIT_LIST_PRICE" : "11.89",
"UNIT_SELLING_PRICE" : "11.89",
"CALCULATE_PRICE_FLAG" : "N",
"OPERATION_CODE" : "INSERT"
}, {
"ORIG_SYS_DOCUMENT_REF" : "Order666",
"ORIG_SYS_LINE_REF" : "3",
"CUSTOMER_LINE_NUMBER" : "3",
"ITEM_TYPE_CODE" : "STANDARD",
"ITEM_DESCRIPTION" : "SKU9999",
"USER_ITEM_DESCRIPTION" : "SKU9999",
"TOP_MODEL_LINE_REF" : null,
"LINK_TO_LINE_REF" : null,
"COMPONENT_CODE" : null,
"ORDERED_QUANTITY" : "8",
"ORDER_QUANTITY_UOM" : null,
"UNIT_LIST_PRICE" : "46.42",
"UNIT_SELLING_PRICE" : "46.42",
"CALCULATE_PRICE_FLAG" : "N",
"OPERATION_CODE" : "INSERT"
} ]
} ]
}
}
I've been trying to learn how to use this JSON with SQL server pretty much starting from today. I've explored the OPENJSON() function which like I've said, I can define the separate columns and path with the header information - but as soon as I try to do similar and path to the detail objects, I just get NULLs back in each column.
Any suggestions at all? Apologies if I've missed any key information out here! Many thanks!
Something like this:
declare #json nvarchar(max) = '
{
"InputParameters" : {
"P_IN_ORDER_SOURCE" : "The_Web",
"P_IN_ORIG_SYS_DOCUMENT_REF" : "Order666",
"P_IN_SOLD_TO_CUST_NUMBER" : "JOEB11",
"P_IN_CUST_ORDER_NUMBER" : "JoeB5556667",
"P_IN_REQUEST_DATE" : "2021-01-20 08:10:06",
"P_IN_ORDER_ENTRY_DATE" : "2021-01-20 08:10:06",
"P_IN_SHIPTO_NAME" : "The Testing Co.",
"P_IN_SHIPTO_ADDR" : "82 Annweir Crescent",
"P_IN_SHIPTO_ADDR_2" : null,
"P_IN_SHIPTO_CITY" : "Atlantis",
"P_IN_SHIPTO_STATE" : "WSX",
"P_IN_SHIPTO_ZIP" : "AT55 666",
"P_IN_SHIPTO_COUNTRY" : "GB",
"P_IN_OPERATION_CODE" : "CREATE",
"P_IN_BOOKED_FLAG" : "N",
"P_IN_OU_NAME" : "ATL UK OU",
"P_IN_SPECIAL_INSTRUCTIONS" : null,
"P_IN_QUOTE_NUMBER" : null,
"P_IN_PRICELIST_ID" : "8",
"P_IN_EMAIL" : "testemail#testemail.com",
"P_IN_SHIPTO_COUNTY" : null,
"P_IN_SHIPPING_METHOD" : "Pre 930",
"P_IN_SHIPPING_INSTRUCTIONS" : null,
"P_IN_ATTENTION_TO" : "Joe Bloggs",
"P_IN_FREIGHT_CARRIER_CODE" : null,
"P_IN_IS_RETURN" : null,
"P_IN_SALES_REP" : null,
"P_IN_LINE_DATA" : [ {
"P_IN_LINE_DATA_ITEM" : [ {
"ORIG_SYS_DOCUMENT_REF" : "Order666",
"ORIG_SYS_LINE_REF" : "1",
"CUSTOMER_LINE_NUMBER" : "1",
"ITEM_TYPE_CODE" : "STANDARD",
"ITEM_DESCRIPTION" : "SKU7776",
"USER_ITEM_DESCRIPTION" : "SKU7776",
"TOP_MODEL_LINE_REF" : null,
"LINK_TO_LINE_REF" : null,
"COMPONENT_CODE" : null,
"ORDERED_QUANTITY" : "6",
"ORDER_QUANTITY_UOM" : null,
"UNIT_LIST_PRICE" : "16.95",
"UNIT_SELLING_PRICE" : "16.95",
"CALCULATE_PRICE_FLAG" : "N",
"OPERATION_CODE" : "INSERT"
}, {
"ORIG_SYS_DOCUMENT_REF" : "Order666",
"ORIG_SYS_LINE_REF" : "2",
"CUSTOMER_LINE_NUMBER" : "2",
"ITEM_TYPE_CODE" : "STANDARD",
"ITEM_DESCRIPTION" : "SKU12345",
"USER_ITEM_DESCRIPTION" : "SKU12345",
"TOP_MODEL_LINE_REF" : null,
"LINK_TO_LINE_REF" : null,
"COMPONENT_CODE" : null,
"ORDERED_QUANTITY" : "6",
"ORDER_QUANTITY_UOM" : null,
"UNIT_LIST_PRICE" : "11.89",
"UNIT_SELLING_PRICE" : "11.89",
"CALCULATE_PRICE_FLAG" : "N",
"OPERATION_CODE" : "INSERT"
}, {
"ORIG_SYS_DOCUMENT_REF" : "Order666",
"ORIG_SYS_LINE_REF" : "3",
"CUSTOMER_LINE_NUMBER" : "3",
"ITEM_TYPE_CODE" : "STANDARD",
"ITEM_DESCRIPTION" : "SKU9999",
"USER_ITEM_DESCRIPTION" : "SKU9999",
"TOP_MODEL_LINE_REF" : null,
"LINK_TO_LINE_REF" : null,
"COMPONENT_CODE" : null,
"ORDERED_QUANTITY" : "8",
"ORDER_QUANTITY_UOM" : null,
"UNIT_LIST_PRICE" : "46.42",
"UNIT_SELLING_PRICE" : "46.42",
"CALCULATE_PRICE_FLAG" : "N",
"OPERATION_CODE" : "INSERT"
} ]
} ]
}
}
'
select *
from openjson(#json,'$.InputParameters.P_IN_LINE_DATA[0].P_IN_LINE_DATA_ITEM')
with
(
ORIG_SYS_DOCUMENT_REF varchar(200),
ORIG_SYS_LINE_REF int,
CUSTOMER_LINE_NUMBER int,
ITEM_TYPE_CODE varchar(200),
-- . . .
OPERATION_CODE varchar(200)
)
i want to send json body to my middleware. at first, it works well (note that the "tema" & "emailGroup" wasn't an array). but after some changes on my backend, i have to send this type of json
[{
"ID": "",
"Name": "Artikel BU CE - Visit HoB Topic",
"ChannelType": 0,
"PublishDate": "2018-09-21T01:00:00Z",
"Headline": null,
"Content": null,
"EmailSubject": null,
"EmailUrl": null,
"Mention": null,
"PostLink": null,
"ChannelActivityMobileId": null,
"HashTag": null,
"Tema": [
{
"Value": 6
}
],
"EmailGroup": [
{
"ID": "2c53ea1f-6ebe-e811-a977-000d3aa00fc2",
"Name": "TV Broadcast",
"List_EmailListModels": null
}
],
"ApprovalStatus": 0,
"ApprovalNote": null,
"EmployeeId": null,
"EmployeeLevel": 0
}]
here's my code
let parameters = [["ID" : "", SerializationKeys.channelMobileId : channel.mobileId, SerializationKeys.name : activity.activityName, "ApprovalStatus" : channel.channelStatus, SerializationKeys.channelType : channel.channelType, SerializationKeys.publish_date : channel.publishDate, SerializationKeys.content : channel.content, SerializationKeys.emailSubject : channel.emailSubject, SerializationKeys.emailURL : channel.emailURL, SerializationKeys.hashtag : channel.hastag, SerializationKeys.mention : channel.mention, SerializationKeys.note : channel.note, SerializationKeys.postLink : channel.postLink, SerializationKeys.tema : [tema]] as [[String : Any]]
where tema is
var tema = [String : Int]()
i got an error that says
[Any] is not convertible to '[[String : Any]]'; did you mean to use as! to force downcast?
and after i change "as" to "as!", it says
Excpected ";" separator
where the semicolon should put near "SerializationKeys.tema : [tema]". Please kindly help me. Thanks
EDIT
I think you mistakenly added ] near
, SerializationKeys.postLink : channel.postLink],
You may want this
let parameters:[[String:Any]] = [["ID" : "",
SerializationKeys.channelMobileId : channel.mobileId,
SerializationKeys.name : activity.activityName,
"ApprovalStatus" : channel.channelStatus,
SerializationKeys.channelType : channel.channelType,
SerializationKeys.publish_date : channel.publishDate,
SerializationKeys.content : channel.content,
SerializationKeys.emailSubject : channel.emailSubject,
SerializationKeys.emailURL : channel.emailURL,
SerializationKeys.hashtag : channel.hastag,
SerializationKeys.mention : channel.mention,
SerializationKeys.note : channel.note,
SerializationKeys.postLink : channel.postLink,
SerializationKeys.tema : [tema]
]]
Note: I heighly recommend using Codable with struct models for your case
Below is the JSON file I am trying to read nodes from. I am trying to perform contains operation. I do not want to use equals option in my json path like this - $.[?(#.name=="College Graduate - Ford")]
Could you please help me in meeting my requirement?
[
{
"incentiveId" : 123,
"autoApplied" : "false",
"name" : "College Graduate - Ford",
"amount" : 750,
"expirationDate" : "2018-12-31",
"minimumTerm" : null,
"maximumTerm" : null,
"groupAffiliation" : "College/Student",
"previousOwnership" : null
},
{
"incentiveId" : 456,
"autoApplied" : "false",
"name" : "Lease Loyalty - Ford",
"amount" : 500,
"expirationDate" : "2018-07-09",
"groupAffiliation" : null,
"previousOwnership" : "Lease Loyalty"
},
{
"incentiveId" : 789,
"autoApplied" : "false",
"name" : "Customer Cash - Ford",
"amount" : 1000,
"expirationDate" : "2018-06-04",
"groupAffiliation" : null,
"previousOwnership" : null
},
{
"incentiveId" : 222,
"autoApplied" : "false",
"name" : "Military - Ford",
"amount" : 1000,
"expirationDate" : "2018-12-31",
"groupAffiliation" : "Military",
"previousOwnership" : null
}
]
$.[?(/College/.test(#.name))]
Here I am using the test the RegExp test( ) method (which JSONPath evals behind the scenes) . This will perform the contains operation.
you can use filter to get array from array which elements satisfy the condition.
colleagues = json.filter(node => node.name.match("College"))
result:
[
{
"incentiveId": 123,
"autoApplied": "false",
"name": "College Graduate - Ford",
"amount": 750,
"expirationDate": "2018-12-31",
"minimumTerm": null,
"maximumTerm": null,
"groupAffiliation": "College/Student",
"previousOwnership": null
}
]