This page includes scripts that may be useful either in and of themselves, or as a start point for your own scripting work.
PHP
Converting JSON to CSV
<?php
function handle($data) {
// Decode the JSON string into an array
$dataArray = json_decode($data['payload'], true);
if ($dataArray === null) {
// JSON decoding failed
return 'Failed to decode JSON.';
}
// Create an empty array to store the CSV rows
$csvRows = [];
// Add the CSV headers
if (!empty($dataArray)) {
$headers = array_keys($dataArray[0]);
$csvRows[] = $headers;
}
// Add the CSV rows
foreach ($dataArray as $row) {
$csvRows[] = array_values($row);
}
// Generate the CSV string
$csvString = '';
foreach ($csvRows as $row) {
$csvString .= implode(',', $row) . "\n";
}
// Return the CSV string or error message
return ['payload' => !empty($csvString) ? $csvString : 'Failed to convert JSON to CSV'];
}
C#
This script takes an XML input string, loads it into an XmlDocument, and then converts that XML to a JSON string using the Newtonsoft.Json library.
Converting XML to JSON
using System;
using System.Xml;
using Newtonsoft.Json;
public class FunctionHandler
{
public string Handle(string input)
{
var xmlDoc = new XmlDocument();
// Set up XML namespace manager
var namespaceManager = new XmlNamespaceManager(xmlDoc.NameTable);
namespaceManager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
namespaceManager.AddNamespace("", "http://api.jdplc.com/schemas/mc/pim/feproducts");
// Load the XML string into XmlDocument
xmlDoc.LoadXml(input);
// Convert the XML to JSON
string jsonText = JsonConvert.SerializeXmlNode(xmlDoc, Newtonsoft.Json.Formatting.Indented, true);
return jsonText;
}
}