How can I extract the JSON-encapsulated CSV contents returned by the SpecConnect API?
The SpecConnect API may format the results of certain requested reports as CSV encapsulated within a standard JSON-formatted response. To extract the contents of the result which can more readily be imported into programs like Excel or Numbers, here are a couple of sample scripts that might be useful after storing the JSON response to a file.
Using a Powershell script (Windows):
# Path to the JSON file
$jsonFilePath = "C:\path\to\your\file.json"
# Specify the field to extract
$fieldToExtract = "Csv"
# Path to the output CSV file
$outputFilePath = "C:\path\to\your\output.csv"
# Import JSON data
$jsonData = Get-Content -Path $jsonFilePath | ConvertFrom-Json
# Extract the field and output to console
$jsonData | ForEach-Object { $_.$fieldToExtract } | Set-Content -Path $outputFilePath
Using bash with jq (Linux/MacOS):
#!/bin/bash
# Path to the JSON file
jsonFilePath="/path/to/your/file.json"
# Path to the output text file
outputFilePath="/path/to/your/output.csv"
# Specify the field to extract
fieldToExtract="Csv" # Replace with the actual field name
# Extract the field and save to file
# Make sure jq is installed by running jq --version;
# You can install it with:
# Debian/Ubuntu: sudo apt-get install jq
# macOS: brew install jq
# RHEL: sudo yum install epel-release
# sudo yum install jq
jq -r ".$fieldToExtract" "$jsonFilePath" > "$outputFilePath"
Using bash without jq (Linux/MacOS):
#!/bin/bash
# Path to the JSON file
jsonFilePath="/path/to/your/file.json"
# Path to the output text file
outputFilePath="/path/to/your/output.csv"
# Specify the field to extract
fieldToExtract="Csv" # Replace with the actual field name
# Extract the field and save to file
grep -o "\"$fieldToExtract\": *\".*[^\\]\" *," "$jsonFilePath" |
sed -E "s/\"$fieldToExtract\": *\"(.*)\" *,$/\1/" |
sed -E 's/\\r//g' |
sed -E 's/\\"/"/g' |
sed -E 's/\\n/\n/g' > "$outputFilePath"