Powershell - Cannot parse JSON - Get NotSpecified error - json

Code used to try parsing file
$myJson = Get-Content cleantest2.json -Raw | ConvertFrom-Json
Get below error when trying to parse JSON file.
$myJson = Get-Content cleantest2.json -Raw | ConvertFrom-Json
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [ConvertFrom-Json], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.ConvertFromJsonCommand
EDIT: As noted, the above error was truncated because it was too long. Here is the full error.
ConvertFrom-Json : Invalid object passed in, ':' or '}' expected. (2): {"id":0,"resourcePackage
s":[{"resourcePackage":{"name":"SharedResources","type":2,"i
tems":[{"type":202,"path":"BaseThemes/CY18SU07.json","name"
:"CY18SU07"}],"disabled":false}}],"sections":[{"id":0,"name"
:"ReportSection","displayName":"Page 1","filters":"[]","ord
inal":0,"visualContainers":[{"x":10,"y":0,"z":1,"width":280,
"height":280,"config":"{\"name\":\"5a0b8ef6c97162087ff7\",\
"layouts\":[{\"id\":0,\"position\":{\"x\":10,\"y\":0,\"width
\":280,\"height\":280,\"z\":1}}],\"singleVisual\":{\"visual
Type\":\"tableEx\",\"projections\":{\"Values\":[{\"queryRef\
":\"servers_and_applications.App Name\"},{\"queryRef\":\"se
rvers_and_applications.Cust_Nme\"},{\"queryRef\":\"servers_a
nd_applications.MU_ID\"}]},\"prototypeQuery\":{\"Version\":
2,\"From\":[{\"Name\":\"s\",\"Entity\":\"servers_and_applica
tions\"}],\"Select\":[{\"Column\":{\"Expression\":{\"Source
Ref\":{\"Source\":\"s\"}},\"Property\":\"App
Name\"},\"Name\":\"servers_and_applications.App Name\"},{\"
Column\":{\"Expression\":{\"SourceRef\":{\"Source\":\"s\"}},
\"Property\":\"Cust_Nme\"},\"Name\":\"servers_and_applicati
ons.Cust_Nme\"},{\"Column\":{\"Expression\":{\"SourceRef\":{
\"Source\":\"s\"}},\"Property\":\"MU_ID\"},\"Name\":\"serve
rs_and_applications.MU_ID\"}]},\"drillFilterOtherVisuals\":t
rue}}","filters":"[]","query":"{\"Commands\":[{\"SemanticQu
eryDataShapeCommand\":{\"Query\":{\"Version\":2,\"From\":[{\
"Name\":\"s\",\"Entity\":\"servers_and_applications\"}],\"S
elect\":[{\"Column\":{\"Expression\":{\"SourceRef\":{\"Sourc
e\":\"s\"}},\"Property\":\"App
Name\"},\"Name\":\"servers_and_applications.App Name\"},{\"
Column\":{\"Expression\":{\"SourceRef\":{\"Source\":\"s\"}},
\"Property\":\"Cust_Nme\"},\"Name\":\"servers_and_applicati
ons.Cust_Nme\"},{\"Column\":{\"Expression\":{\"SourceRef\":{
\"Source\":\"s\"}},\"Property\":\"MU_ID\"},\"Name\":\"serve
rs_and_applications.MU_ID\"}]},\"Binding\":{\"Primary\":{\"G
roupings\":[{\"Projections\":[0,1,2],\"Subtotal\":1}]},\"Da
taReduction\":{\"DataVolume\":3,\"Primary\":{\"Window\":{\"C
ount\":500}}},\"Version\":1}}}]}","dataTransforms":"{\"proj
ectionOrdering\":{\"Values\":[0,1,2]},\"queryMetadata\":{\"S
elect\":[{\"Restatement\":\"App
Name\",\"Name\":\"servers_and_applications.App Name\",\"Typ
e\":2048},{\"Restatement\":\"Cust_Nme\",\"Name\":\"servers_a
nd_applications.Cust_Nme\",\"Type\":2048},{\"Restatement\":
\"MU_ID\",\"Name\":\"servers_and_applications.MU_ID\",\"Type
\":2048}]},\"visualElements\":[{\"DataRoles\":[{\"Name\":\"
Values\",\"Projection\":0,\"isActive\":false},{\"Name\":\"Va
lues\",\"Projection\":1,\"isActive\":false},{\"Name\":\"Val
ues\",\"Projection\":2,\"isActive\":false}]}],\"selects\":[{
\"displayName\":\"App
Name\",\"queryName\":\"servers_and_applications.App Name\",
\"roles\":{\"Values\":true},\"type\":{\"category\":null,\"un
derlyingType\":1},\"expr\":{\"Column\":{\"Expression\":{\"S
ourceRef\":{\"Entity\":\"servers_and_applications\"}},\"Prop
erty\":\"App Name\"}}},{\"displayName\":\"Cust_Nme\",\"quer
yName\":\"servers_and_applications.Cust_Nme\",\"roles\":{\"V
alues\":true},\"type\":{\"category\":null,\"underlyingType\
":1},\"expr\":{\"Column\":{\"Expression\":{\"SourceRef\":{\"
Entity\":\"servers_and_applications\"}},\"Property\":\"Cust
_Nme\"}}},{\"displayName\":\"MU_ID\",\"queryName\":\"servers
_and_applications.MU_ID\",\"roles\":{\"Values\":true},\"typ
e\":{\"category\":null,\"underlyingType\":1},\"expr\":{\"Col
umn\":{\"Expression\":{\"SourceRef\":{\"Entity\":\"servers_
and_applications\"}},\"Property\":\"MU_ID\"}}}]}"}],"config"
:"{}","displayOption":1,"width":1280,"height":720}],"config
":"{\"version\":\"3.19\",\"themeCollection\":{\"baseTheme\":
{\"name\":\"CY18SU07\",\"version\":\"3.22\",\"type\":2}},\"
activeSectionIndex\":0,\"defaultDrillFilterOtherVisuals\":tr
ue,\"settings\":{\"useStylableVisualContainerHeader\":true,
\"exportDataMode\":1}}","layoutOptimization":0}
At line:1 char:46
+ $myJson = Get-Content cleantest2.json -Raw | ConvertFrom-Json
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [ConvertFrom-Json], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.ConvertFromJsonCommand
Below is file that was trying to get parsed.
{"id":0,"resourcePackages":[{"resourcePackage":{"name":"SharedResources","type":2,"items":[{"type":202,"path":"BaseThemes/CY18SU07.json","name":"CY18SU07"}],"disabled":false}}],"sections":[{"id":0,"name":"ReportSection","displayName":"Page 1","filters":"[]","ordinal":0,"visualContainers":[{"x":10,"y":0,"z":1,"width":280,"height":280,"config":"{\"name\":\"5a0b8ef6c97162087ff7\",\"layouts\":[{\"id\":0,\"position\":{\"x\":10,\"y\":0,\"width\":280,\"height\":280,\"z\":1}}],\"singleVisual\":{\"visualType\":\"tableEx\",\"projections\":{\"Values\":[{\"queryRef\":\"servers_and_applications.App Name\"},{\"queryRef\":\"servers_and_applications.Cust_Nme\"},{\"queryRef\":\"servers_and_applications.MU_ID\"}]},\"prototypeQuery\":{\"Version\":2,\"From\":[{\"Name\":\"s\",\"Entity\":\"servers_and_applications\"}],\"Select\":[{\"Column\":{\"Expression\":{\"SourceRef\":{\"Source\":\"s\"}},\"Property\":\"App Name\"},\"Name\":\"servers_and_applications.App Name\"},{\"Column\":{\"Expression\":{\"SourceRef\":{\"Source\":\"s\"}},\"Property\":\"Cust_Nme\"},\"Name\":\"servers_and_applications.Cust_Nme\"},{\"Column\":{\"Expression\":{\"SourceRef\":{\"Source\":\"s\"}},\"Property\":\"MU_ID\"},\"Name\":\"servers_and_applications.MU_ID\"}]},\"drillFilterOtherVisuals\":true}}","filters":"[]","query":"{\"Commands\":[{\"SemanticQueryDataShapeCommand\":{\"Query\":{\"Version\":2,\"From\":[{\"Name\":\"s\",\"Entity\":\"servers_and_applications\"}],\"Select\":[{\"Column\":{\"Expression\":{\"SourceRef\":{\"Source\":\"s\"}},\"Property\":\"App Name\"},\"Name\":\"servers_and_applications.App Name\"},{\"Column\":{\"Expression\":{\"SourceRef\":{\"Source\":\"s\"}},\"Property\":\"Cust_Nme\"},\"Name\":\"servers_and_applications.Cust_Nme\"},{\"Column\":{\"Expression\":{\"SourceRef\":{\"Source\":\"s\"}},\"Property\":\"MU_ID\"},\"Name\":\"servers_and_applications.MU_ID\"}]},\"Binding\":{\"Primary\":{\"Groupings\":[{\"Projections\":[0,1,2],\"Subtotal\":1}]},\"DataReduction\":{\"DataVolume\":3,\"Primary\":{\"Window\":{\"Count\":500}}},\"Version\":1}}}]}","dataTransforms":"{\"projectionOrdering\":{\"Values\":[0,1,2]},\"queryMetadata\":{\"Select\":[{\"Restatement\":\"App Name\",\"Name\":\"servers_and_applications.App Name\",\"Type\":2048},{\"Restatement\":\"Cust_Nme\",\"Name\":\"servers_and_applications.Cust_Nme\",\"Type\":2048},{\"Restatement\":\"MU_ID\",\"Name\":\"servers_and_applications.MU_ID\",\"Type\":2048}]},\"visualElements\":[{\"DataRoles\":[{\"Name\":\"Values\",\"Projection\":0,\"isActive\":false},{\"Name\":\"Values\",\"Projection\":1,\"isActive\":false},{\"Name\":\"Values\",\"Projection\":2,\"isActive\":false}]}],\"selects\":[{\"displayName\":\"App Name\",\"queryName\":\"servers_and_applications.App Name\",\"roles\":{\"Values\":true},\"type\":{\"category\":null,\"underlyingType\":1},\"expr\":{\"Column\":{\"Expression\":{\"SourceRef\":{\"Entity\":\"servers_and_applications\"}},\"Property\":\"App Name\"}}},{\"displayName\":\"Cust_Nme\",\"queryName\":\"servers_and_applications.Cust_Nme\",\"roles\":{\"Values\":true},\"type\":{\"category\":null,\"underlyingType\":1},\"expr\":{\"Column\":{\"Expression\":{\"SourceRef\":{\"Entity\":\"servers_and_applications\"}},\"Property\":\"Cust_Nme\"}}},{\"displayName\":\"MU_ID\",\"queryName\":\"servers_and_applications.MU_ID\",\"roles\":{\"Values\":true},\"type\":{\"category\":null,\"underlyingType\":1},\"expr\":{\"Column\":{\"Expression\":{\"SourceRef\":{\"Entity\":\"servers_and_applications\"}},\"Property\":\"MU_ID\"}}}]}"}],"config":"{}","displayOption":1,"width":1280,"height":720}],"config":"{\"version\":\"3.19\",\"themeCollection\":{\"baseTheme\":{\"name\":\"CY18SU07\",\"version\":\"3.22\",\"type\":2}},\"activeSectionIndex\":0,\"defaultDrillFilterOtherVisuals\":true,\"settings\":{\"useStylableVisualContainerHeader\":true,\"exportDataMode\":1}}","layoutOptimization":0}
Reformatted:
{
"id": 0,
"resourcePackages": [
{
"resourcePackage": {
"name": "SharedResources",
"type": 2,
"items": [
{
"type": 202,
"path": "BaseThemes/CY18SU07.json",
"name": "CY18SU07"
}
],
"disabled": false
}
}
],
"sections": [
{
"id": 0,
"name": "ReportSection",
"displayName": "Page 1",
"filters": "[]",
"ordinal": 0,
"visualContainers": [
{
"x": 10,
"y": 0,
"z": 1,
"width": 280,
"height": 280,
"config": "{\"name\":\"5a0b8ef6c97162087ff7\",\"layouts\":[{\"id\":0,\"position\":{\"x\":10,\"y\":0,\"width\":280,\"height\":280,\"z\":1}}],\"singleVisual\":{\"visualType\":\"tableEx\",\"projections\":{\"Values\":[{\"queryRef\":\"servers_and_applications.App Name\"},{\"queryRef\":\"servers_and_applications.Cust_Nme\"},{\"queryRef\":\"servers_and_applications.MU_ID\"}]},\"prototypeQuery\":{\"Version\":2,\"From\":[{\"Name\":\"s\",\"Entity\":\"servers_and_applications\"}],\"Select\":[{\"Column\":{\"Expression\":{\"SourceRef\":{\"Source\":\"s\"}},\"Property\":\"App Name\"},\"Name\":\"servers_and_applications.App Name\"},{\"Column\":{\"Expression\":{\"SourceRef\":{\"Source\":\"s\"}},\"Property\":\"Cust_Nme\"},\"Name\":\"servers_and_applications.Cust_Nme\"},{\"Column\":{\"Expression\":{\"SourceRef\":{\"Source\":\"s\"}},\"Property\":\"MU_ID\"},\"Name\":\"servers_and_applications.MU_ID\"}]},\"drillFilterOtherVisuals\":true}}",
"filters": "[]",
"query": "{\"Commands\":[{\"SemanticQueryDataShapeCommand\":{\"Query\":{\"Version\":2,\"From\":[{\"Name\":\"s\",\"Entity\":\"servers_and_applications\"}],\"Select\":[{\"Column\":{\"Expression\":{\"SourceRef\":{\"Source\":\"s\"}},\"Property\":\"App Name\"},\"Name\":\"servers_and_applications.App Name\"},{\"Column\":{\"Expression\":{\"SourceRef\":{\"Source\":\"s\"}},\"Property\":\"Cust_Nme\"},\"Name\":\"servers_and_applications.Cust_Nme\"},{\"Column\":{\"Expression\":{\"SourceRef\":{\"Source\":\"s\"}},\"Property\":\"MU_ID\"},\"Name\":\"servers_and_applications.MU_ID\"}]},\"Binding\":{\"Primary\":{\"Groupings\":[{\"Projections\":[0,1,2],\"Subtotal\":1}]},\"DataReduction\":{\"DataVolume\":3,\"Primary\":{\"Window\":{\"Count\":500}}},\"Version\":1}}}]}",
"dataTransforms": "{\"projectionOrdering\":{\"Values\":[0,1,2]},\"queryMetadata\":{\"Select\":[{\"Restatement\":\"App Name\",\"Name\":\"servers_and_applications.App Name\",\"Type\":2048},{\"Restatement\":\"Cust_Nme\",\"Name\":\"servers_and_applications.Cust_Nme\",\"Type\":2048},{\"Restatement\":\"MU_ID\",\"Name\":\"servers_and_applications.MU_ID\",\"Type\":2048}]},\"visualElements\":[{\"DataRoles\":[{\"Name\":\"Values\",\"Projection\":0,\"isActive\":false},{\"Name\":\"Values\",\"Projection\":1,\"isActive\":false},{\"Name\":\"Values\",\"Projection\":2,\"isActive\":false}]}],\"selects\":[{\"displayName\":\"App Name\",\"queryName\":\"servers_and_applications.App Name\",\"roles\":{\"Values\":true},\"type\":{\"category\":null,\"underlyingType\":1},\"expr\":{\"Column\":{\"Expression\":{\"SourceRef\":{\"Entity\":\"servers_and_applications\"}},\"Property\":\"App Name\"}}},{\"displayName\":\"Cust_Nme\",\"queryName\":\"servers_and_applications.Cust_Nme\",\"roles\":{\"Values\":true},\"type\":{\"category\":null,\"underlyingType\":1},\"expr\":{\"Column\":{\"Expression\":{\"SourceRef\":{\"Entity\":\"servers_and_applications\"}},\"Property\":\"Cust_Nme\"}}},{\"displayName\":\"MU_ID\",\"queryName\":\"servers_and_applications.MU_ID\",\"roles\":{\"Values\":true},\"type\":{\"category\":null,\"underlyingType\":1},\"expr\":{\"Column\":{\"Expression\":{\"SourceRef\":{\"Entity\":\"servers_and_applications\"}},\"Property\":\"MU_ID\"}}}]}"
}
],
"config": "{}",
"displayOption": 1,
"width": 1280,
"height": 720
}
],
"config": "{\"version\":\"3.19\",\"themeCollection\":{\"baseTheme\":{\"name\":\"CY18SU07\",\"version\":\"3.22\",\"type\":2}},\"activeSectionIndex\":0,\"defaultDrillFilterOtherVisuals\":true,\"settings\":{\"useStylableVisualContainerHeader\":true,\"exportDataMode\":1}}",
"layoutOptimization": 0
}
Items attempted:
Used online formator on text and then re-ran command on resulting string. - Worked
Tried to import raw string and export as JSON using ConverTo-Json method but didn't work correctly.
Tried parsing using Python but had similar issue.

I was able to fix this by changing the encoding to unicode. See below sample execution.
$myJson = Get-Content cleantest2.json -Encoding unicode | ConvertFrom-Json

Your own answer implies that your input file, cleantest2.json, was malformed:
The fact that -Encoding Unicode solved your problem implies that the file is a UTF-16LE-encoded file that lacks a BOM, which means that it provides no indication to readers of the file what its encoding is, and causes Get-Content to (justifiably) misinterpret the file.
Consider correcting the problem at the source: make the creator of file cleantest2.json create it with the appropriate BOM, the way that Set-Content -Encoding Unicode does, for instance.
As for troubleshooting your symptom:
If a string's display output is seemingly correct, but processing of the string doesn't work as expected, the cause is usually the presence of hidden control characters.
Specifically, misreading a BOM-less UTF16-LE ("Unicode") file as either ANSI-encoded (which Windows PowerShell does by default) or UTF-8 (as PowerShell (Core) 7+ does by default) results in all ASCII-range characters being followed by a NUL character (code point 0x0)each, and these NUL characters are invisible when you print the string.
For testing, you can create a malformed UTF-16LE file as follows:
# Write 'foo' with UTF-16LE encoding to file 'cleantest2.json' *without a BOM*:
[IO.File]::WriteAllText("$PWD/cleantest2.json", "f`0o`0`o`0")
A simple test for the presence of at least one NUL character (expressed as "`0" in PowerShell) is:
(Get-Content cleantest2.json -Raw) -match "`0" # "`0" creates a NUL
Piping to Format-Hex can also help in this case:[1]
# Look for `00` values.
Get-Content cleantest2.json -Raw | Format-Hex
The Debug-String helper function, available from this MIT-licensed Gist offers a direct visualization:
# Download and define the Debug-String function.
# NOTE:
# I can personally assure you that doing this is safe, but you
# you should always check the source code first.
irm https://gist.github.com/mklement0/7f2f1e13ac9c2afaf0a0906d08b392d1/raw/Debug-String.ps1 | iex
Get-Content cleantest2.json -Raw | Debug-String
Output:
A note re spotting the problem with the help of text editors:
This may not help, because many editors correctly detect UTF-16LE files even without a BOM (e.g., Notepad, Visual Studio Code), and in their status bar report just "UTF-16 LE" whether or not a BOM is present.
However, if an editor offers a hex view (of the bytes that make up the file), you'll be able to tell: If an UTF-16LE file does have a BOM, the first two bytes are FF FE (for UTF-8 files that have a BOM, the first three bytes are EF BB BF).
Visual Studio Code has a Hex Editor extension
js2010 reports that Emacs has a hexl-mode.
[1] Use of Format-Hex to discover (non-ASCII-range) Unicode characters isn't an option in Windows PowerShell, because it represents any non-ASCII chars. as 3f, i.e. literal ?. In PowerShell (Core) it shows the ASCII rendering of the individual bytes that make up the UTF-8 encoding of non-ASCII characters, which can be confusing.

Related

Push JSON file with special chars unicode to bigquery via command line

Im trying to push a json file to BQ via bqcmd which contains special chars such as ü but tis failing. Ive tried differnt encoding etc. nothing workign except removing the chars
{
"productName": "soft drüum",
"Category": "xxxxxxx",
"subCategory": "Sun & Tan",
"subSubCategory": "Sun",
"productType": "Standard",
"brandName": "soft drüum",
"quantity": 1
}
Json File was successful until introduction of special chars
BQ command:
bq load --autodetect=true --time_partitioning_field date
--source_format NEWLINE_DELIMITED_JSON Data.products D:\XXXX\xx\products.json
I would check to make sure that you have your json saved as new line delimited. In your example, the trailing comma is not valid in New Line Delimited JSON.
I was able to then upload these special characters via this command:
bq load --project_id=${project_id} --source_format NEWLINE_DELIMITED_JSON --autodetect ${database}.${table} ${nldjson_filename}

Convert a JSON representation of CSV data to actual CSV data

This self-answered question is about transforming a JSON representation of CSV data into actual CSV data.[1]
The following JSON contains separate properties that describe the headers (column names) (columns) and arrays of corresponding row values (rows), respectively:
{
"columns": [
{
"name": "ColumnName1",
"type": "Number"
},
{
"name": "ColumnName2",
"type": "String"
},
{
"name": "ColumnName3",
"type": "String"
}
],
"rows": [
[
11111,
"ResourceType1",
"String1"
],
[
22222,
"ResourceType2",
"String2"
],
[
33333,
"ResourceType3",
"String3"
]
]
}
How can I convert this JSON input to the CSV data it represents?
[1] The question duplicates this closed question, which was closed presumably due to lack of effort, even though what it asks for is reasonably well-defined.
Note that CSV files have no concept of data types - all values are strings,
so the data-type information (from the .column.type properties) is lost, unless you choose to incorporate it
in some way as a convention that the consumer of the CSV would have to be aware of (the code below does not do that).
Assume that the JSON in the question is saved in file file.json, which can be parsed into a ([pscustomobject]) object graph with ConvertFrom-Json, via reading the file as text with Get-Content:
# Convert the JSON text into a [pscustomobject] object graph.
$fromJson = ConvertFrom-Json (Get-Content -Raw file.json)
# Process the array of column names and the arrays of row values by
# enclosing the array elements in "..." and joining them with ","
(, $fromJson.Columns.Name + $fromJson.Rows).ForEach({
$_.ForEach({ '"{0}"' -f ($_ -replace '"', '""') }) -join ','
})
Note that the above encloses the column names and values in "..." so as to also support
names and values with embedded , characters; additionally, any embedded " characters are properly escaped by doubling them.
If you know that the input data neither contains values with embedded , nor
", you can simply omit the inner .ForEach() array method
call above, which will result in unquoted values.
The above outputs:
"ColumnName1","ColumnName2","ColumnName3"
"11111","ResourceType1","String1"
"22222","ResourceType2","String2"
"33333","ResourceType3","String3"
To convert the above in-memory to ([pscustomobject]) objects representing the CSV data, use ConvertFrom-Csv (... represents the command above):
... | ConvertFrom-Csv
To save the above to a CSV file, use Set-Content:
... | Set-Content -Encoding utf8 out.csv

Pass JSON variable to AzureDevops Release definition

My goal is to pass a JSON object from one machine to another using the AzureDevops pipeline variables.
The process starts with a powershell script that obtains the JSON object and compresses it to:
$json=[{"test":"foo","bar":"hello}].
Please note that it will be always an array.
Now, I set the azure variable with:
Write-Host "##vso[task.setvariable variable=Json]$json"
now the variable is initialized in the release pipeline BUT, the double quotes are not escaped.
That means that when I try to obtain the $(Json) in the next script it fails due to invalid characters of course. My question is, how can escape those double quotes? I have tried adding single quotes to the beginning and the end of the string but it won't work. Thanks!
You may try the following format for the JSON file:
$json = #"
[
{
"op": "add",
"path": "/fields/System.Title",
"value": "Bug22"
},
{
"op": "add",
"path": "/fields/Microsoft.VSTS.Common.Severity",
"value": "3 - Medium"
}
]
"# | ConvertTo-Json -Compress
Have you tried wrapping the pipeline variable with a here-string before using it?
$json = #"
$(Json)
"#

How to keep UTF-8 encoding when sorting JSON with jq

I'm using jq 1.5 on Windows PowerShell to sort the fields of a JSON file in an alphabetically order.
This works quite fine so far but special characters (like ÜÄÖüäö) are not kept in the jq output.
The original file is saved in UTF-8 encoding:
{
"sha": "18879fb99367924cd76d402e841155bf73c8afb3",
"commit": {
"author": {
"name": "John Doe ÜÄÖ",
"email": "john#example.com",
"date": "2017-11-23T07:51:22Z"
}
}
}
And this is the jq output saved as UTF-8:
{
"commit": {
"author": {
"date": "2017-11-23T07:51:22Z",
"email": "john#example.com",
"name": "John Doe ???"
}
},
"sha": "18879fb99367924cd76d402e841155bf73c8afb3"
}
As you can see the characters ÜÄÖ are not recognized and are saved as ???.
This is how I use jq in PowerShell:
$json = Get-Content .\json.txt -Encoding UTF8
$jsonSorted = $json | .\jq-win64.exe --sort-keys '.'
Set-Content jsonSorted.txt -Value $jsonSorted -Encoding UTF8
You don’t mention which version of jq you are using, but I strongly suspect you have encountered a bug which has since been fixed. I believe the most recent UTF-8 bug was fixed by
https://github.com/stedolan/jq/pull/1317
in late January. Unfortunately, this means that for a fix, you’ll most likely need a version of jq more recent than 1.5.
Since you are using Windows, I would suggest looking at https://github.com/stedolan/jq/wiki/Installation#windows-using-appveyor
Code Page
Maybe changing the code page will help? At the command prompt, first run chcp to ascertain the current code page; if it is not already 65001, run chcp 65001.
See also https://superuser.com/questions/237081/whats-the-code-page-of-utf-8
Verification on a Mac
$ file john-doe.json
john-doe.json: UTF-8 Unicode text
$ cat john-doe.json
"John Doe ÜÄÖ"
$ jq --version
jq-1.5
$ jq . john-doe.json
"John Doe ÜÄÖ"
$ jqMaster --version
jq-1.5rc2-250-g239278f
$ jqMaster . john-doe.json
"John Doe ÜÄÖ"
I tried everything mentioned here and still got incorrect output. I had to set [System.Console]::OutputEncoding=[System.Text.Encoding]::UTF8 in PowerShell and then it works as expected. That's actually the only thing I had to do.

"Invalid array passed" when parsing JSON

I have this file which I want to read with PowerShell:
var myMap =
[
{
"name": "JSON Example",
"attr": "Another attribute"
}
]
My PowerShell v3 Code:
$str = Get-Content $file | Select -Skip 1;
$str | ConvertFrom-Json;
But I'm always getting this error:
ConvertFrom-Json : Invalid array passed in, ']' expected. (1): [
At S:\ome\Path\script.ps1:60 char:8
+ $str | ConvertFrom-Json;
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [ConvertFrom-Json], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.ConvertFromJsonCommand
If I copy and paste the JSON code manually into the code, everything is working fine:
'[
{
"name": "JSON Example",
"attr": "Another attribute"
}
]' | ConvertFrom-Json;
Try to pipe to Out-String before piping to ConvertFrom-Json:
Get-Content $file | Select -Skip 1 | Out-String | ConvertFrom-Json
In your working example the JSON code is a string while the non-working example returns a collection of lines. Piping to Out-String converts the collection to a single string, which is what the InputObject parameter accept.
Alternatively you can use Get-Content -Raw which will retrieve the JSON as a single string.
See this post for more info: http://blogs.technet.com/b/heyscriptingguy/archive/2014/04/23/json-is-the-new-xml.aspx
The var myMap = isn't json, it's javascript. Delete the first line and it will be fine.
EDIT:
Oh, you are skipping the first line. It may be that there's a carriage return missing in the last line of the file, and Powershell 3 is more sensitive to it. It works fine in Powershell 5.1 even without a carriage return at the end.
another answer that also works: use GC -raw <FILE> which will pass in as string