JSON Generator Tool

<#
.SYNOPSIS
JSON Generator Tool

.DESCRIPTION
This script provides an interactive tool to create JSON structures, add objects, arrays,
and key-value pairs, and export the resulting JSON to a file.

.NOTES
File Name      : JSONGenerator.ps1
Author         : [Your Name]
Prerequisite   : PowerShell V5.1 or later
Version        : 1.0
Date           : [Current Date]

.EXAMPLE
.\JSONGenerator.ps1
#>

# Global variables
$script:jsonObject = @{}
$script:currentPath = @()
$script:jsonFilePath = "$env:USERPROFILE\Desktop\Generated_JSON_$(Get-Date -Format 'yyyyMMdd_HHmmss').json"

function Show-Menu {
    Clear-Host
    Write-Host "=== JSON Generator Tool ===" -ForegroundColor Cyan
    Write-Host "Current Path: $(if ($script:currentPath.Count -eq 0) { 'Root' } else { $script:currentPath -join '.' })"
    Write-Host "1. Add Key-Value Pair"
    Write-Host "2. Add Object"
    Write-Host "3. Add Array"
    Write-Host "4. Move to Parent"
    Write-Host "5. View Current JSON Structure"
    Write-Host "6. Export JSON to File"
    Write-Host "7. Exit"
}

function Add-KeyValuePair {
    $key = Read-Host "Enter the key"
    $value = Read-Host "Enter the value"

    # Try to convert the value to appropriate type
    if ($value -eq "true" -or $value -eq "false") {
        $value = [System.Convert]::ToBoolean($value)
    }
    elseif ($value -match "^\d+$") {
        $value = [int]$value
    }
    elseif ($value -match "^\d*\.\d+$") {
        $value = [double]$value
    }

    $current = Get-CurrentObject
    $current[$key] = $value
    Write-Host "Key-Value pair added." -ForegroundColor Green
}

function Add-Object {
    $key = Read-Host "Enter the key for the new object"
    $current = Get-CurrentObject
    $current[$key] = @{}
    $script:currentPath += $key
    Write-Host "Object added and set as current path." -ForegroundColor Green
}

function Add-Array {
    $key = Read-Host "Enter the key for the new array"
    $current = Get-CurrentObject
    $current[$key] = @()
    $script:currentPath += $key
    Write-Host "Array added and set as current path." -ForegroundColor Green

    do {
        $addItem = Read-Host "Do you want to add an item to the array? (Y/N)"
        if ($addItem -eq 'Y') {
            $item = Read-Host "Enter the item value"
            # Try to convert the value to appropriate type
            if ($item -eq "true" -or $item -eq "false") {
                $item = [System.Convert]::ToBoolean($item)
            }
            elseif ($item -match "^\d+$") {
                $item = [int]$item
            }
            elseif ($item -match "^\d*\.\d+$") {
                $item = [double]$item
            }
            $current[$key] += $item
            Write-Host "Item added to array." -ForegroundColor Green
        }
    } while ($addItem -eq 'Y')
}

function Move-ToParent {
    if ($script:currentPath.Count -eq 0) {
        Write-Host "Already at root level." -ForegroundColor Yellow
        return
    }
    $script:currentPath = $script:currentPath[0..($script:currentPath.Count - 2)]
    Write-Host "Moved to parent." -ForegroundColor Green
}

function Get-CurrentObject {
    $current = $script:jsonObject
    foreach ($key in $script:currentPath) {
        $current = $current[$key]
    }
    return $current
}

function View-CurrentJSON {
    $jsonString = $script:jsonObject | ConvertTo-Json -Depth 10
    Write-Host "Current JSON Structure:" -ForegroundColor Yellow
    Write-Host $jsonString
}

function Export-JSONToFile {
    try {
        $jsonString = $script:jsonObject | ConvertTo-Json -Depth 10
        $jsonString | Out-File -FilePath $script:jsonFilePath -Encoding UTF8
        Write-Host "JSON exported successfully to: $script:jsonFilePath" -ForegroundColor Green
    }
    catch {
        Write-Host "Error exporting JSON: $_" -ForegroundColor Red
    }
}

# Main program loop
do {
    Show-Menu
    $choice = Read-Host "`nEnter your choice (1-7)"

    switch ($choice) {
        "1" { Add-KeyValuePair }
        "2" { Add-Object }
        "3" { Add-Array }
        "4" { Move-ToParent }
        "5" { View-CurrentJSON }
        "6" { Export-JSONToFile }
        "7" { Write-Host "Exiting program..." -ForegroundColor Yellow; break }
        default { Write-Host "Invalid choice. Please try again." -ForegroundColor Red }
    }

    if ($choice -ne "7") {
        Read-Host "`nPress Enter to continue..."
    }
} while ($choice -ne "7")

This JSON Generator Tool includes:

  1. A menu-driven interface for easy navigation.
  2. Functions to interactively build JSON structures:
    • Add key-value pairs
    • Add nested objects
    • Add arrays and array items
    • Navigate the JSON structure (move to parent)
  3. Ability to view the current JSON structure at any time.
  4. Option to export the generated JSON to a file.

Key features:

  • Interactive JSON creation process
  • Support for nested objects and arrays
  • Automatic type conversion for values (boolean, integer, double, string)
  • Hierarchical navigation within the JSON structure
  • Real-time viewing of the current JSON structure
  • Export functionality to save the generated JSON

This tool is particularly useful for:

  • Developers who need to create JSON structures for testing or configuration purposes
  • Anyone learning about JSON structure and wanting to experiment with creating JSON documents
  • System administrators who need to generate JSON files for various applications
  • Quality Assurance professionals creating JSON test data

To use this script effectively:

  1. Run the script in PowerShell
  2. Use the menu options to build your JSON structure:
    • Add key-value pairs for simple data
    • Add objects for nested structures
    • Add arrays for lists of items
    • Use the “Move to Parent” option to navigate back up the JSON tree
  3. View the current JSON structure at any time to check your progress
  4. When finished, export the JSON to a file

This script provides a user-friendly way to create JSON structures without having to manually write JSON syntax. It’s especially helpful for those who are new to JSON or need to quickly generate JSON files without writing them by hand. The tool also handles proper nesting and type conversion, ensuring that the generated JSON is valid and properly formatted.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *