I have an array of objects in JSON format coming in on the request. I would like to transform these objects into single line JSON (JSONL) in the velocity mapping template. Is this possible?
Going from:
[
{
"something": "else",
"another": "thing"
},
{
"something": "else",
"another": "thing"
}
]
Into
{ "something": "else", "another": "thing" }
{ "something": "else", "another": "thing" }
Any help would be much appreciated.
Something along those lines?
#foreach( $entry in $array )
## make sure $entry is a string
#set( $entry = "$entry" )
## merge lines
#set( $entry = $entry.replaceAll('\n', '') )
## print line
$entry
#end
Related
I am trying to convert below Json table to Json array object, below json failed because of there is single nested json object, but its working when there are multiple objects in nested json
[
{
"name": "PrimaryResult",
"columns": [
{
"name": "Computer",
"type": "string"
},
{
"name": "LastHeartbeat",
"type": "datetime"
}
],
"rows": [
[
"xxxxxxx.dev.org",
"2022-01-19T04:49:48.937Z"
]
]
}
]
Expected output is as below
[
{
"Computer": xxxxxxx.dev.org",
"LastHeartbeat": "2022-01-19T04:49:48.937Z"
}
]
I have tried with the below Json script it works when there are multiple objects in array
[
{
"name": "PrimaryResult",
"columns": [
{
"name": "Computer",
"type": "string"
},
{
"name": "LastHeartbeat",
"type": "datetime"
}
],
"rows": [
[
"zzzzz.test.org",
"2022-01-04T09:06:45.44Z"
],
[
"yyyy.dev.org",
"2022-01-04T09:06:30.233Z"
],
[
"xxxx.prod.org",
"2022-01-04T09:06:08.893Z"
],
[
"xxxx.dev.org",
"2022-01-04T09:06:04.667Z"
]
]
}
]
I have tried with below powershell script
=============================================
$TriggerMetadata = Get-Content .\test4.json | ConvertFrom-Json
$affected_resources = $TriggerMetadata.tables
$resources =
ForEach($Row in $affected_resources.rows)
{
$TmpHash = [Ordered]#{}
For($i = 0; $i -lt $Row.Length; $i++ )
{
$TmpHash.Add($affected_resources.columns.name[$i], $Row[$i] )
}
[PSCustomObject]$TmpHash
}
$body = $resources | ConvertTo-Json -Depth 100
$Body
Getting below error
Exception calling "Add" with "2" argument(s): "Key cannot be null.
Parameter name: key"
At line:22 char:13
+ $TmpHash.Add($affected_resources.columns.name[$i], $Row[$ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentNullException
PowerShell 'unravels' arrays when there is only one element in it.
In this case that produces the error you encounter you can fix by using the , unary comma operator which will wrap the single element of the input array into another single element array.
When PowerShell unwraps that, the result is the original array of row values from the json file
Assuming you have the JSON converted in a variable $json:
$headers = $json.columns.name
# if there is only one 'rows 'element, wrap it in an array by prefixing with comma
if ($json.rows[0] -is [array]) { $rows = $json.rows } else { $rows = ,$json.rows }
$resources = $rows | ForEach-Object {
$hash = [ordered]#{}
for ($i = 0; $i -lt $headers.Count; $i++) {
$hash[$headers[$i]] = $_[$i]
}
[PsCustomObject]$hash
}
Output:
{
"Computer": "zzzzz.test.org",
"LastHeartbeat": "2022-01-04T09:06:45.44Z"
}
If you really do need the square brackets around that, you can do the test as before and enclose the result in '[..]'
if ($json.rows[0] -is [array]) {
$body = $resources | ConvertTo-Json -Depth 100
}
else {
$body = "[ {0} ]" -f ($resources | ConvertTo-Json -Depth 100)
}
Output:
[ {
"Computer": "zzzzz.test.org",
"LastHeartbeat": "2022-01-04T09:06:45.44Z"
} ]
I want to validate from PowerShell using this JSON
{
"Customer": {
"OnSubscription": true,
"Name": "John",
"Surname": "Smith"
},
"Data": {
"Basket": [
"apples",
"pears",
"oranges",
"strawberries"
]
}
}
here is my script
$json = Get-Content .\basket.json | ConvertFrom-Json
param(
[string[]]$param = "Customer"
)
Write-Host $param
if ($param -eq $json) {
Write-Host "Valid Customer Key"}
else
{
$message = "Invalid Customer Key"
Write-Host $message
}
$output = ($json.$param.PSObject.Properties.Name | ForEach-Object {
"$_={0}" -f $json.$param.$_
}) -join "`n"
$Path2 = ".\output\env"
$output | Out-File $Path2
The parameter create for checking the JSON, is there a valid customer key or not?
For example, input param ABC, but in JSON there is no ABC. So its showing message like "Invalid Customer Key". When condition is valid customer key, Its showing message like "Valid Customer Key"
but the result I always got "Invalid Customer Key"
Is something wrong with if condition?
You might want to clean your code up a bit and dont think with such complexity. Your Task is quite easy, I have mocked something up for you.
loadMe.Json
{
"content":[
{
"Customer":{
"OnSubscription":true,
"Name":"John",
"Surname":"Smith"
},
"Data":{
"Basket":[
"apples",
"pears",
"oranges",
"strawberries"
]
}
},
{
"Customer":{
"OnSubscription":true,
"Name":"John2",
"Surname":"Smith"
},
"Data":{
"Basket":[
"apples",
"pears",
"oranges",
"strawberries"
]
}
},
{
"Customer":{
"OnSubscription":true,
"Name":"John3",
"Surname":"Smith"
},
"Data":{
"Basket":[
"apples",
"pears",
"oranges",
"strawberries"
]
}
}
]
}
Step One - Get Content of Json into an Object
$myJson = Get-Content -Path (Join-Path $PSScriptRoot '\loadMe.json') | ConvertFrom-json
Step Two - Loop through content and match names
foreach($item in $myJson.content) {
if($item.Customer.Name -eq $myOtherVariable) {
...
}
}
The following code gives the wanted output, task accomplished
$myJson = Get-Content -Path (Join-Path $PSScriptRoot '\loadMe.json') | ConvertFrom-json
foreach($item in $myJson.content) {
Write-Host $item.Customer.Name
}
Output -->
John
John2
John3
I have Json strings in the database I am fetching those with sql query , I need to update this json values with another value how can achieve that .
{
"ssoredr": [
"xyz",
"abc",
"def",
"zas"
],
"allowedOther": {
"FUNDSERV": "dfghj",
"CINS": "dfghj",
"ESDID": "fghjk",
"Compliance Science ID": "3456",
"OSI IDENTIFIER": "6789"
},
"mftConfiguration": {
"connectionName": "UK-Only",
"archiveFolder": "/xyz/ua/Archive/"
}
}
I need to update mftconfigaration with another value
Using ConvertFrom-Json
$json = #"
{
"ssoredr": [
"xyz",
"abc",
"def",
"zas"
],
"allowedOther": {
"FUNDSERV": "dfghj",
"CINS": "dfghj",
"ESDID": "fghjk",
"Compliance Science ID": "3456",
"OSI IDENTIFIER": "6789"
},
"mftConfiguration": {
"connectionName": "UK-Only",
"archiveFolder": "/xyz/ua/Archive/"
}
}
"# | ConvertFrom-Json
$json.mftConfiguration.connectionName = "US-Only"
$json | ConvertTo-Json | Out-File c:\text.json # convert back to json string and save to a new file or overwrite the source
I am trying to iterate through some JSON when the exact structure is unknown.
This JSON looks like this:
"object" : {
"Item1" : {
"property1" : "a"
"property2" : "b"
}
}
"Item2" : {
"property1" : "c"
"property2" : "d"
}
}
}
The problem is, I don't know what the actual name of Item1 or Item2 is going to be. It is a string of alphanumeric characters that is different on each call.
I have tried
$json_response = $response.object
foreach($item in $json_response) {
$id = $item.property1
Write-Host $id
}
However the $id value never gets set to the value of proprty1. The Write-Host always prints out an empty string.
If I simply do a
Write-Host $json_response
I get something like
#{Item1=; item2=}
I thought this may have been a hash table that would allow me to iterate through it using keys, but there is no Keys property.
Can anyone assist?
Update: Lee_Dailey's response has gotten me further, but still cannot access the properties. With Lee_Dailey's help, I have come up with the following:
foreach ($item in $response_json.PSobject.Properties) {
$json2 = $item | ConvertTo-Json
Write-Host $json2
}
This creates the following JSON
{
"Value": {
"property1": "a",
"property2": "b"
}
}
However I still cannot access property1. Doing
$id = json2.Value.property1
Write-Host $id
results in an empty value. How do I access the properties in the JSON in the $json2 variable?
Update 2. I think I got it working, but I don't know if this is correct or a hack. Updating the code from above to
$json2 = $item | ConvertTo-Json | ConvertFrom-Json
Seems to allow me to do
$id = $json2.Value.property1
I am not sure where "Value" came from. It is not part of the HTTP response. It also seems odd to convert to JSON and then convert it back, however that seems to expose the properties.
I'm guessing the json is supposed to be this. These badly structured objects are common. You can loop through properties of "object" using either .psobjects.properties or get-member. Also, in newer versions of powershell, you can convert json to hashtable and use the keys property.
{
"object": {
"Item1": {
"property1": "a",
"property2": "b"
}
},
"Item2": {
"property1": "c",
"property2": "d"
}
}
See also: Iterating through a JSON file PowerShell
In an ideal world, it would look like this. But it comes out more verbose.
{
"object": [
{
"name": "Item1",
"value": [
{
"name": "property1",
"value": "a"
},
{
"name": "property2",
"value": "b"
}
]
},
{
"name": "Item2",
"value": [
{
"name": "property1",
"value": "c"
},
{
"name": "property2",
"value": "d"
}
]
}
]
}
$a = cat file.json | convertfrom-json
$a.object
name value
---- -----
Item1 {#{name=property1; value=a}, #{name=property2; value=b}}
Item2 {#{name=property1; value=c}, #{name=property2; value=d}}
$a.object.value
name value
---- -----
property1 a
property2 b
property1 c
property2 d
I have one document in my "params" collection like this:
{
"_id": ObjectId("4d124cef3ffcf6f410000037"),
"code": "color",
"productTypes": [
{
"$ref": "productTypes",
"$id": ObjectId("4d120a2d2b8d8d3010000000"),
"$db": "test"
}
]
}
the referenced document is this:
{
"_id": ObjectId("4d120a2d2b8d8d3010000000"),
"code": "car"
}
I'm using DoctrineODM to fetch the "param" documents which referenced "productType" is "car". I'm using this code:
$query = $dm->createQuery('Cms\Model\Param');
$query->field('productTypes.code')->equals('car');
$result = $query->execute();
var_dump($result);
but the result is an empty array. How can i do this?
If you using ReferenceMany or ReferenceOne you can't query by any reference document field, except reference document id.
If you need query on code from referenced collection you should use EmbedMany instead of ReferenceMany.
In this case your document will be:
{
"_id": ObjectId("4d124cef3ffcf6f410000037"),
"code": "color",
"productTypes": [
{
"_id": ObjectId("4d120a2d2b8d8d3010000000"),
"code": "car"
}
]
}
And following query will work:
$query = $dm->createQuery('Cms\Model\Param');
$query->field('productTypes.code')->equals('car');
$result = $query->execute();
var_dump($result);
Also if your ProductType code is unique you can use it instead of MongoId, in this case you can query on $id:
{
"_id": ObjectId("4d124cef3ffcf6f410000037"),
"code": "color",
"productTypes": [
{
"$ref": "productTypes",
"$id": 'car',
"$db": "test"
}
]
}
Referenced document:
{
"_id": 'car'
}
Query:
$query->field('productTypes.$id')->equals('car');
You must use the references() method of Query Builder for a #MongoDB\ReferenceOne like https://doctrine-mongodb-odm.readthedocs.org/en/latest/reference/query-builder-api.html
$productType = $dm->getRepository('Cms\Model\ProductTypes')->findOneByCode('car');
$queryBuilder = $dm->getRepository('Cms\Model\Param')->createQueryBuilder()
->field('productTypes')->references($productType);
$results = $queryBuilder->getQuery()->execute();
PS: use includesReferenceTo() a #MongoDB\ReferenceMany
->field('productTypes.code')->equals(new \MongoRegex('/.*car.*/i'))