Convert to JSON with comments from PowerShell

powershell json = get value by key
powershell convert string to json
powershell convertfrom-json
json comment
powershell read json file
powershell json array of objects
powershell create json file
powershell convertfrom-json array

I have a very simple json and this code works for him:

function Get-CustomHeaders() {
   return Get-Content -Raw -Path $JsonName | ConvertFrom-Json
}

However, if my json has any comments // wololo it breaks. Would it be too hard to make this parser accept comments ?

The solution in the other answer only removes // comments if they are at the beginning of a line (with or without spaces), and doesn't remove /* multiline comments */

This code removes all kind of // and /* multiline comments *//

$configFile = (Get-Content path-to-jsonc-file -raw)
# Keep reading, for an improvement
# $configFile = $configFile -replace '(?m)\s*//.*?$' -replace '(?ms)/\*.*?\*/'

As @Jiří Herník indicates in his answer, this expression doesn't have into account the case of strings with comments inside it, for example "url": "http://mydomian.com". To handle this case:

$configFile = $configFile -replace '(?m)(?<=^([^"]|"[^"]*")*)//.*' -replace '(?ms)/\*.*?\*/'

for example removing the comments in this file:

{
  // https://github.com/serilog/serilog-settings-configuration
  "Serilog": {
    "MinimumLevel": "Error", // Verbose, Debug, Information, Warning, Error or Fatal
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "D:\\temp\\MyService\\log.txt",
          "rollingInterval": "Day",
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] ({App}) ({Environment}) {Message:lj}{NewLine}{Exception}"
        }
      },
      {/*
        "Name": "Seq",*/
        "Args": {
          "serverUrl": "http://localhost:5341"
        }
      }
    ]
  }
}

results in:

{

  "Serilog": {
    "MinimumLevel": "Error",
    "WriteTo": [
      {
        "Name": "File",
        "Args": {
          "path": "D:\\temp\\MyService\\log.txt",
          "rollingInterval": "Day",
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] ({App}) ({Environment}) {Message:lj}{NewLine}{Exception}"
        }
      } ,
      {
        "Args": {
          "serverUrl": "http://localhost:5341"
        }
      }
    ]
  }
}

ConvertFrom-Json (Microsoft.PowerShell.Utility), Remove comment lines from your input before the conversion: (Get-Content $ JsonName) -replace '^\s*//.*' | Out-String | ConvertFrom-Json� The PowerShell cmdlets ConvertFrom-Json and ConvertTo-Json enable you to read a raw JavaScript Object Notation (JSON) string and convert it to a nice PowerShell object. Or you can go the other way and convert a PowerShell object into a JSON string.

Remove comment lines from your input before the conversion:

(Get-Content $JsonName) -replace '^\s*//.*' | Out-String | ConvertFrom-Json

ConvertTo-Json (Microsoft.PowerShell.Utility), "JSON with Comments" with the jsonc file extension is a natively Can you provide some example JSON, example PowerShell code, what you� Summary: Windows PowerShell MVP, Doug Finke, discusses using a simple Windows PowerShell command to convert to or from JSON. Microsoft Scripting Guy, Ed Wilson, is here. Today we have guest blogger, Doug Finke. Microsoft Windows PowerShell MVP, Doug Finke is the author of Windows PowerShell for Developers.

Here you have an example which can't be handled right by previous answers:

{
"url":"http://something" // note the double slash in URL
}

so here is regexp that solves also this problem.

$configFile = $configFile -replace '(?m)(?<=^([^"]|"[^"]*")*)//.*' -replace '(?ms)/\*.*?\*/'

IMPORTANT NOTE:

Powershell 6.0+ can load JSON with comments in it.

Convert to JSON with comments from PowerShell - json - html, A simple JSON example ^. Of course, you can also manage JSON in PowerShell. Let's start by using an example JSON string representing� One of the cool cmdlets in Windows PowerShell 5.0 on Windows 10 is the ConvertFrom-JSON cmdlet. One reason it is cool is that it will convert a Java Script Object Notation (JSON) string into a custom Windows PowerShell object. This is a cool way to interact with web services, and it can save a bit of time from parsing XML.

Add `.jsonc` support to `ConvertFrom-Json` � Issue #7436 , We convert the data from the variable $vPSObject to JSON format. Json. In the previous example, the flow of data was JSON, then PowerShell� PowerShell is a cross-platform (Windows, Linux, and macOS) automation tool and configuration framework optimized for dealing with structured data (e.g. JSON, CSV, XML, etc.), REST APIs, and object models.

Convert JSON with the PowerShell cmdlets ConvertFrom-Json and , The Convert*-Json cmdlets were introduced with Windows like you via the PowerShell GitHub repository through issues, comments, voting,� I am writing a script to make changes to a JSON file but when the file is converted back to JSON it expands special characters. For example the JSON File contain passwords with "&". A quick way to replicate the problem is using following command: PS> "Password&123" | Convertto-Json output is:"Password\u0026123"

Using JSON with PowerShell: A guide for IT professionals, Convert an object to a JSON-formatted string. Syntax ConvertTo-Json [- InputObject] Object [-Compress] [-Depth Int32] [CommonParameters] Key - InputObject� ConvertTo-Xml returns an in-memory representation of an XML document, so you can continue to process it in PowerShell. ConvertTo-Xml does not have an option to convert objects to CLI XML. Examples Example 1: Convert a date to XML PS C:\> Get-Date | ConvertTo-Xml. This command converts the current date (a DateTime object) to XML.

Comments
  • JSON (by definition, the spec) does not support comments.
  • that is true, and i apreciate the info. But for this case i sadly need the comments. You know how it works in our world =P
  • Then you're going to need to figure out how to parse them out: -join (Get-Content -Path $JsonName) -replace '^//.*' | ConvertFrom-Json
  • There is issue in the powershell project for adding jsonc support: github.com/PowerShell/PowerShell/issues/7436
  • This will also catch two slashes in here "serverUrl": "//localhost:5341", you cannot see it, because it's inside of other comment block in your example.
  • For multi-line /*...*/ style comments you can use (Get-Content $JsonName) -replace '(?ms)/*.*?*/' -replace '//.*'
  • @stimms You need to read the file as a whole and to escape asterisks that you don't want to be treated as wildcards: (gc $jsonname -raw) -replace '(?ms)/\*.*?\*/' ...
  • You also need to ignore // which are inside double quotes, e.g. in the case of a URL configuration value. (Get-Content 'appsettings.json' -raw) -replace '(?<=^([^"]|"[^"]*")*)//.*'
  • Also, PowerShell Core 6 supports comments in Json files out of the box