0

I'm stuck trying to figure out the correct format to read the values from JSON data in powershell.

Input JSON

    {
    "last_time": "2020-01-13T16:39:37.000Z",
    "sensors": {
        "1929": [{
            "observed": "2020-01-13T16:38:39.000Z",
            "humidity": 26.26,
            "temperature": 66.55
        }],
        "2032": [{
            "observed": "2020-01-13T16:38:50.000Z",
            "humidity": 22.87,
            "temperature": 74.6
        }],
        "2198": [{
            "observed": "2020-01-13T16:39:37.000Z",
            "humidity": 31.14,
            "temperature": 62.79
        }]
    },
    "truncated": false,
    "status": "OK",
    "total_samples": 3,
    "total_sensors": 3
    }

Desired Output

    <prtg><result><channel>2198 temperature</channel><value>62.79</value></result></prtg>

I can work out the conversion to XML just fine, but i have been banging my head trying to sort out how to read the actual property value in powershell when the key is all numeric in quotes.

I've tried things like:

    write-Output $sp.sensors.2198[0].temperature

How does one escape the 2198?

1

3 Answers 3

1

Make it a string

$sp.sensors."2198".temperature
Sign up to request clarification or add additional context in comments.

Comments

0

Since your Property name is a string of number, you will have to first assign the value of integer key and then access the value of that variable.

$newObj = $jsonObj.sensors.1929
$newObj.temperature

# Or Put Parenthesis around it.
($jsonObj.sensors.1929)[0].temperature

You can use, PSObject.Properties to get the properties and iterate over them as well.

$Json = Get-Content C:\temp\fileWithJsonData
$jsonObj = $Json | ConvertFrom-Json
$jsonObj.sensors.PSObject.Properties | % { $_.Name }

Output

1929
2032
2198

You can then iterate through each of the properties like this as well to get the values for each.

foreach($prop in $jsonObj.sensors.PSObject.Properties) 
{ 
    write-output "$($prop.Name) $($prop.value[0].observed) $($prop.value[0].humidity) $($prop.value[0].temperature)" 
}

Output

 1929 2020-01-13T16:38:39.000Z 26.26 66.55
 2032 2020-01-13T16:38:50.000Z 22.87 74.6
 2198 2020-01-13T16:39:37.000Z 31.14 62.79

Comments

0

Here's a get-member version. See also Iterate over PSObject properties in PowerShell

$Json = Get-Content file.json
$jsonObj = $Json | ConvertFrom-Json
$jsonObj.sensors | get-member -Type Properties | % name

1929
2032
2198

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.