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?

Jawad
  • 11,028
  • 3
  • 24
  • 37
DDulla
  • 659
  • 9
  • 20
  • Does this answer your question? [Json Error: Missing property name after reference operator](https://stackoverflow.com/questions/49170644/json-error-missing-property-name-after-reference-operator) – BenH Jan 13 '20 at 18:56

3 Answers3

1

Make it a string

$sp.sensors."2198".temperature
vrdse
  • 2,899
  • 10
  • 20
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
Jawad
  • 11,028
  • 3
  • 24
  • 37
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
js2010
  • 23,033
  • 6
  • 64
  • 66