2

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.

6
  • 2
    which part is the powershell? Commented May 31, 2018 at 5:57
  • If I were you, I'd forget powershell. Upload the json files on your webserver, and use ajax requests (I recommend axios) to fetch them. Something along the lines of axios.get('jsonfiles/file1.json').then(function(response){ var town_XXtown_name = L.marker(map.unproject([response.data.coords.x, response.data.coords.u], map.getMaxZoom())).bindPopup(`<h1>${response.data.Description.Name}</h1>`); (Not complete, but I think you get the picture.) '` jQuery has a [.get()] as well if that is more familiar. Same thing (jquery does 1000 of things, axios only does the ajax requests). Commented May 31, 2018 at 6:10
  • I just know powershell would be a great candidate to extract this kind of information as i've used similar query functions in the past but only for single points of data. Anything that can do it would be fine, i just know powershell is capable of it and would quite commonly used. All im wanting powershell to do is read the jsons, and print out the information, but not just give me a list of each location and its info, but insert the relevant points to where they are needed within the example js code i put in the OP Commented May 31, 2018 at 6:11
  • thanks ippi but not what i want to do at all. i dont want 350 jsons on the server being queired constantly. they contain 100x the data i need to complete the task Im wanting to do. I only need the data listed in the example, not 3-600 lines of text in 350 jsons. i know what i'm asking is quite simple for powershell to do and it can be done, i've seen the end result from others in the past, just dont know how to. Plus you seem to be missing hte whole point. with your example i would still need to put that code in for EVERY marker, powershell can print that info and i paste it into my html Commented May 31, 2018 at 6:15
  • Alright, I see your point and I learned a thing or two reading up about powershell and convertTo-json. Just saying, javascript and json is like bread and butter. Powershell is clearly the overhead here. May I suggest a node-script instead? (sorry!) Commented May 31, 2018 at 6:36

3 Answers 3

2

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

knowledge is to be shared, not haorded! hopefully it will help someone else in the future
1

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

Comments

0

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.

5 Comments

thanks, would achieve an acceptable result. but yet again the setup would require typing out hundreds individual parameters so it knows what to call from, the answer i listed automatically reads from every separate json by itself without having to know their names. appreciate hte input though, will save it for possible later use!
Aha, I thought that was the requirement when to only pull the data you wanted. But yes, you'd need a babel plugin to support import * from './folder' in node for now.
yeh again, this script is not for JS, its to read jsons in powershell and gives back a fully working JS code you can dump directly into your file. one script that automatically searches all the folders and files and pools all the data into a working code. which is exactly what my powershell main man did for me below
I do not deny that I cherry pick three files, (but you could get all with a jsonGlob('**/*.json') or babel-wildcard import * from '../somefolder'). But yet again, I must also insist that this node-script DOES read jsons from whatever folder you want and outputs a fully working javascript file.
And most of all I don't deny no one even wanted a node-solution, so the point is moot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.