Jilreign
Jilreign

Reputation: 53

Print data from JSONs using Powershell

Since i'm getting answers not related to what i'm trying to achieve I'll just make it as simple as i can.

Multiple separate jsons in the same format each containing the information of individual locations.

All i want powershell to do is take this:

{
    "Description": {
        "Id": "town_breezeholme",
        "Name": "Breezeholme",
        "Blurb": "This quiet town on the outskirts has prospered almost 
completely independently from the surrounding civilisation for nearly 200 years 
due to it's vast wealth accumulated from rich, fertile farmlands, rivers and 
shipping ports.",
        "Authority": "Jeraxian Warriors",
    },
   "coords": {
    "x": 66.4,
    "y": -418.2,
    "z": 34
 },
"tags": {
        "items": [
        "store_jewelers",
        "store_bank",
        "store_general_goods",
        "store_post_office",
        "climate_sub_tropical" 
]},

and turn it into this:

var town_breezeholme = L.marker(map.unproject([,], map.getMaxZoom()))
.bindPopup(`<h1>Breezeholme</h1><p>This quiet town on the outskirts hasprospered almost completely independently from the surrounding civilisation for nearly 200 years due to it's vast wealth accumulated from rich, fertile farmlands, rivers and shipping ports.</p> \n
    <p>Climate: Sub Tropical  \n
    <p>Stores: Jewelers, Bank, General Goods, Post Office \n
    <p>Authority: Jeraxian Warriors `);

but a few hundred times for each one. all i want is something i can copy and paste into my existing html file so that i dont have to write the above out for every single location myself.

You can ignore the coords, i dont want that info and i dont need the marker arrays, i will put the marker arrays in myself as they the coords will not be the same as the marker arrays.

Upvotes: 2

Views: 74

Answers (3)

f6a4
f6a4

Reputation: 1782

Powershell solution:

function Convert-JsonToHTML {

    param(
        $json )

    $jObject = ConvertFrom-Json $json

    $stores  = ''
    $climate = ''

    $itemCollection = $jObject.tags.items
    foreach( $item in $itemCollection ) {
        $tag = $item -split '_'
        switch( $tag[0] ) {
            'store' {
                $storename = ''
                for( $i = 1; $i -lt $tag.Count; $i++ ) {
                    $storename += $tag[$i].Substring(0,1).ToUpper() + $tag[$i].Substring(1).ToLower()
                }
                $stores += $storename + ', '
                break
            }
            'climate' {
                $climate = ''
                for( $i = 1; $i -lt $tag.Count; $i++ ) {
                    $climate += $tag[$i].Substring(0,1).ToUpper() + $tag[$i].Substring(1).ToLower() + ' '
                }
                $climate = $climate.Trim()
                break
            }

        }
    }

    if( $stores.Length -gt 2 ) {
        $stores = $stores.Substring( 0, $stores.Length - 2)
    }

$out = "var $($jObject.Description.Id) = L.marker(map.unproject([,], map.getMaxZoom()))" +
          ".bindPopup(`<h1>$($jObject.Description.Name)</h1><p>$($jObject.Description.Blurb)</p> \n" +
        "<p>Climate: $($climate)\n" +
        "<p>Stores: $($stores)\n" +
        "<p>Authority: $($jObject.Description.Authority) `);"

    return $out

}



$json = '{ "Description": {
        "Id": "town_breezeholme",
        "Name": "Breezeholme",
        "Blurb": "This quiet town on the outskirts has prospered almost 
                completely independently from the surrounding civilisation 
                for nearly 200 years due to its vast wealth accumulated 
                from rich, fertile farmlands, rivers and shipping ports.",
        "Authority": "Jeraxian Warriors"
        },
    "coords": {
        "x": 66.4,
        "y": -418.2,
        "z": 34
    },
    "tags": {
        "items": [ 
        "store_jewelers",
        "store_bank",
        "store_general_goods",
        "store_post_office",
        "climate_sub_tropical" 
     ]}
}'


Convert-JsonToHTML -json $json

Upvotes: 1

ippi
ippi

Reputation: 10177

I'll share my node-solution then, which noone asked for, but I thought it would be a nice exercise.

import fs from 'fs';

import breezeholme from './towns/breezeholme.json';
import town2 from './towns/town2.json';
import town3 from './towns/town3.json';

let towns = [breezeholme, town2, town3];

const capitalizeTags = function(tagItems, key) {
  return tagItems
    .filter(tag => tag.startsWith(key))
    .map(tag =>
      tag
        .replace(key, '')
        .split('_')
        .map(word => word[0].toUpperCase() + word.substring(1))
        .join(' ')
    )
    .join(', ');
};

towns = towns.map(town => {
  const {x, y} = {...town.coords};
  const {Id, Name, Blurb, Authority} = {...town.Description};
  const climate = capitalizeTags(town.tags.items, 'climate_');
  const stores = capitalizeTags(town.tags.items, 'store_');

  const html = `<h1>${Name}</h1>
            <p>${Blurb}</p>
            <p>Climate: ${climate}</p>
            <p>Stores: ${stores}</p>
            <p>Authority: ${Authority}</p>`;

  return `var ${Id} = L.marker(map.unproject([${x}, ${y}], map.getMaxZoom())).bindPopup(\`${html}\`);`;
});

fs.writeFile('./MyGeneratedJavascript.js', towns.join('\n'), console.error);

I got stuck forever on capitalizing those tags and it's still ugly as sin. I like your powershell solution better. Lessons were learned. Great fun.

Upvotes: 0

Jilreign
Jilreign

Reputation: 53

Got my answer custom built in a few minutes elsewhere. Thanks anyway

##Auto-Generated using "PSProject Builder" Created by Matt Hamende 2018
#######################################################################
#Description: generates wireframe powershell projects
#Features:
## Define ScriptRoot
## Standard Function Libraries
## PSModule Prerequities Loader
## JSON Config File
########################################################################

#Set Default Error Handling - Set to Continue for Production
$ErrorActionPreference = "Stop"

#Define Logger Function
Function Log($message) {
    "$(Get-Date -Format u) | $message"
}

#Define Script Root for relative paths
$RunDir = split-path -parent $MyInvocation.MyCommand.Definition
Log "Setting Location to: $RunDir"
Set-Location $RunDir # Sets directory

## Script Below this line     #######################################################

$SystemDef = Get-ChildItem $RunDir\Data\starsystem

$SystemData = @()

Log "Importing Star System Data..."
ForEach ($star in $SystemDef) {
    $SystemData += (Get-Content $star.FullName) -join "`n" | ConvertFrom-        Json
}

Log "System Data Imported..."

ForEach($System in $SystemData[0..9]){
""

$Tags = ($System.Tags.items -join ", ").Replace("planet_","").Replace("_"," ")
$Employers = $System.ContractEmployers -join ", "
$Biomes = $System.SupportedBiomes -join ", "
$SystemStr = @"
<p>System Name: $($System.Description.Name)</p>
<p>Star Type: $($System.StarType)
<p>Description: $($System.Description.Details)</p>
<p>Owner: $($System.Owner)</p>
<p>Tags: $Tags</p>
    <p>Employers: $Employers</p>
    <p>Biomes: $Biomes</p>
"@
$SystemStr
}

Upvotes: 2

Related Questions