Печать данных из JSON с помощью Powershell - PullRequest
0 голосов
/ 31 мая 2018

Поскольку я получаю ответы, не относящиеся к тому, чего я пытаюсь достичь, я просто сделаю это настолько простым, насколько смогу.

Несколько отдельных jsons в одном формате, каждый из которых содержит информацию об отдельныхместоположения.

Все, что я хочу сделать в PowerShell, это взять:

{
    "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" 
]},

и превратить его в следующее:

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 `);

, но несколько сотен раз для каждого,все, что я хочу, это что-то, что я могу скопировать и вставить в свой существующий HTML-файл, так что мне не нужно самому выписывать вышеприведенное для каждого местоположения.

Вы можете игнорировать координаты, мне не нужна эта информация, и ямне не нужны массивы маркеров, я буду помещать массивы маркеров в себя, поскольку их координаты не будут такими же, как у массивов маркеров.

Ответы [ 3 ]

0 голосов
/ 31 мая 2018

Тогда я поделюсь своим нод-решением, о котором никто не просил, но я подумал, что это будет хорошее упражнение.

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);

Я застрял навсегда на заглавных буквах этих тегов, и это все еще безобразно, как грех.Мне нравится ваше решение PowerShell.Уроки были усвоены.Большое удовольствие.

0 голосов
/ 31 мая 2018

Раствор Powershell:

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
0 голосов
/ 31 мая 2018

Получил мой ответ на заказ за несколько минут в другом месте.Все равно спасибо

##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
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...