satya Narayan mohanty
satya Narayan mohanty

Reputation: 13

Powershell ConvertFrom-Json output json format not correct

I have a json file, i converted that by using ConvertFrom-json but the output i am getting below.

Get-Content ".\example1.JSON" | ConvertFrom-Json

Output i am getting as below

---------------------------------
Result                                                                                                                                                                               
------                                                                                                                                                                               
{@{_id=5f0bdeec01c99848bcbbba07; index=0; guid=a1c59de9-94c9-4a53-9a18-61a35457b7a2; isActive=False; balance=$3,782.46; picture=http://placehold.it/32x32; age=28; eyeColor=blue; ...

But i want this should be in below format because of "{"Result":" it is not coming in proper format can someone suggest how to overcome ?

_id           : 5f0bdeec01c99848bcbbba07
index         : 0
guid          : a1c59de9-94c9-4a53-9a18-61a35457b7a2
isActive      : False
balance       : $3,782.46
picture       : http://placehold.it/32x32
age           : 28
eyeColor      : blue
name          : Tran Rodriquez
gender        : male
company       : VIRVA
email         : [email protected]
phone         : +1 (908) 426-2103
address       : 222 Crosby Avenue, Frierson, Louisiana, 613

Here's sample content of the JSON file:

{
  "Result": [
    {
      "id": 10,
      "name": "shirt",
      "color": "red",
      "_id": "5f0bdeec01c99848bcbbba07",
      "host": "tester1"
    },
    {
      "id": 11,
      "name": "coat",
      "color": "black",
      "price": "$2300"
    }
  ]
}

Upvotes: 1

Views: 491

Answers (1)

mklement0
mklement0

Reputation: 437062

You need to access the .Result property in order to have the (nested) object it contains format properly:

(Get-Content -Raw .\example1.JSON | ConvertFrom-Json).Result

Note the use of -Raw, which makes Get-Content read the file as a whole, as a single string - while not strictly necessary, this speeds up processing, given that ConvertFrom-Json needs to collect all input first anyway.


An object that is nested inside another object as a property value is formatted using a single-line, hash-table literal-like representation, as you've experienced.

A simple example:

PS> [pscustomobject] @{ foo = 1; bar = [pscustomobject] @{ baz = 2 } }

foo bar
--- ---
  1 @{baz=2}

Note the representation of the nested custom object stored in the .bar property.

This hash-table literal-like representation is the stringification of [pscustomobject] instances, as (also) used in expandable strings; e.g., "$([pscustomobject] @{ baz = 2 })" yields '@{baz=2}' - see this answer for details.

Upvotes: 1

Related Questions