How do you get JSON data from an item stored in the media library?

master:\media library\item-name contains a JSON file. Get-Item gets the item itself but I am unable to extract the JSON content with ConvertFrom-Json.

In PowerShell outside of Sitecore Powershell Extensions, this code works as expected:

$data = Get-Content -Raw "C:\Users\me\data.json" | ConvertFrom-Json foreach($item in $data){$item.name
}


When I try to use ConvertFrom-Json in Sitecore Powershell Extensions, I get a "Invalid JSON primitive" error because it's getting the item itself rather than the JSON data I uploaded:

How can I get the JSON data itself out of the item to feed to ConvertFrom-Json?

The data stored on disk in data.json is handled differently between your two examples. In one you are using Get-Content while the other you are not. I'm pretty sure it should work in SPE for media.

Generally media items and the associated blob data is extracted with something like the following:

$item = Get-Item -Path "master:" -Id "{6AA5AA9F-071A-4808-91AC-709FAAFFB310}"$mediaItem = [Sitecore.Data.Items.MediaItem]$item$blobField = $mediaItem.InnerItem.Fields["blob"]$blobField.GetBlobStream()


You could build off of this to read the stream to string using low-level .net APIs and then pass to ConvertFrom-Json. Alternatively, work with Get-Content.

Update:

Looks like it gets easier than I expected.

data.json

{
"array": [
1,
2,
3
],
"boolean": true,
"color": "gold",
"null": null,
"number": 123,
"object": {
"a": "b",
"c": "d"
},
"string": "Hello World"
}

$bytes = Get-Content -Path "master:" -ID "{74E3DA87-CECC-4568-AA16-34189F41F1EC}" -Raw [System.Text.Encoding]::UTF8.GetString($bytes) | ConvertFrom-Json

array   : {1, 2, 3}
boolean : True
color   : gold
null    :
number  : 123
object  : @{a=b; c=d}
string  : Hello World

• Incredibly helpful. Thanks so much. Dec 10, 2022 at 23:49