Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用Powershell从JSON打印数据_Javascript_Json_Powershell - Fatal编程技术网

Javascript 使用Powershell从JSON打印数据

Javascript 使用Powershell从JSON打印数据,javascript,json,powershell,Javascript,Json,Powershell,因为我得到的答案与我想要达到的目标无关,所以我会尽可能地简单 多个格式相同的单独JSON,每个JSON包含各个位置的信息 我只想让powershell做这个: { "Description": { "Id": "town_breezeholme", "Name": "Breezeholme", "Blurb": "This quiet town on the outskirts has prospered almost completel

因为我得到的答案与我想要达到的目标无关,所以我会尽可能地简单

多个格式相同的单独JSON,每个JSON包含各个位置的信息

我只想让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 `);
var town\u breezeholme=L.marker(map.unproject([,],map.getMaxZoom()))
.bindpoppup(`Breezeholme这个位于郊区的安静小镇,由于从富饶肥沃的农田、河流和航运港口积累了大量财富,近200年来几乎完全独立于周围的文明而繁荣起来。

\n 气候:亚热带\n 商店:珠宝店、银行、杂货店、邮局\n 权威:耶拉西亚勇士`);
但是每一个都有几百次。我想要的只是一些我可以复制并粘贴到我现有的html文件中的东西,这样我就不必自己为每个位置写上面的内容了


你可以忽略coords,我不需要这些信息,也不需要标记数组,我将把标记数组放在我自己的内存中,因为它们的coords与标记数组不同。

我的答案是在几分钟后在其他地方定制的。无论如何谢谢你

##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
}
使用Matt Hamende 2018创建的“PSProject Builder”自动生成 ####################################################################### #描述:生成线框powershell项目 #特点: ##定义脚本根 ##标准函数库 ##PSModule前置加载程序 ##JSON配置文件 ######################################################################## #设置默认错误处理-设置为继续生产 $ErrorActionPreference=“停止” #定义记录器功能 函数日志($message){ “$(获取日期-格式u)|$消息” } #为相对路径定义脚本根 $RunDir=拆分路径-父级$MyInvocation.MyCommand.Definition 日志“将位置设置为:$RunDir” 设置位置$RunDir#设置目录 ##这行下面的脚本####################################################### $SystemDef=获取子项$RunDir\Data\starsystem $SystemData=@() 日志“导入星体系统数据…” ForEach($SystemDef中的星号){ $SystemData+=(获取内容$star.FullName)-加入“`n”| ConvertFrom-Json } 日志“已导入系统数据…” ForEach($SystemData[0..9]中的系统){ "" $Tags=($System.Tags.items-join“,”).Replace(“行星”,”).Replace(“,”) $Employers=$System.ContractEmployers-join“ $Biomes=$System.SupportedBiomes-加入“,” $SystemStr=@” 系统名称:$($System.Description.Name)

星型:$($System.StarType) 描述:$($System.Description.Details)

所有者:$($System.Owner)

标签:$Tags

雇主:$雇主

生物群落:$生物群落

"@ $SystemStr }
然后我将分享我的节点解决方案,这是无人要求的,但我认为这将是一个很好的练习

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);
从“fs”导入fs;
从“./towns/breezeholme.json”导入breezeholme;
从“./towns/town2.json”导入town2;
从“./towns/town3.json”导入town3;
let towns=[breezeholme,town2,town3];
const capitalizeTags=函数(标记项,键){
返回标记项
.filter(tag=>tag.startsWith(key))
.map(标记=>
标签
.更换(键“”)
.分割
.map(word=>word[0].toUpperCase()+word.substring(1))
.加入(“”)
)
。加入(‘,’);
};
城镇=城镇。地图(城镇=>{
const{x,y}={…town.coords};
const{Id,Name,Blurb,Authority}={…town.Description};
const climate=capitalizedTags(town.tags.items,'climate_');
const stores=capitalizedTags(town.tags.items,'store_');
常量html=`${Name}
${Blurb}

气候:${Climate}

存储:${Stores}

权限:${Authority}

`; 返回'var${Id}=L.marker(map.unproject([${x},${y}],map.getMaxZoom()).bindPopup(\`html}`);`; }); fs.writeFile('./MyGeneratedJavascript.js',towns.join('\n'),console.error);
我一直被那些标签的大写字母所困扰,它仍然是丑陋的罪恶。我更喜欢你的powershell解决方案。吸取了教训。非常有趣

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
函数转换JsonToHTML{
param(
$json)
$jObject=convertfromjson$Json
$stores=''
$climate=''
$itemCollection=$jObject.tags.items
foreach($itemCollection中的项目){
$tag=$item-拆分'\uux'
开关($tag[0]){
“商店”{
$storename=''
对于($i=1;$i-lt$tag.Count;$i++){
$storename+=$tag[$i]。子字符串(0,1).ToUpper()+$tag[$i]。子字符串(1).ToLower()
}
$stores+=$storename+','
打破
}
“气候”{
$climate=''
对于($i=1;$i-lt$tag.Count;$i++){
$climate+=$tag[$i]。子字符串(0,1)。ToUpper()+$tag[$i]。子字符串(1)。ToLower()+''
}
$climate=$climate.Trim()
打破
}
}
}
如果($stores.Length-gt 2){
$stores=$stores.Substring(0,$stores.Length-2)
}
$out=“var$($jObject.Description.Id)=L.marker(map.unproject([,],map.getMaxZoom())”+
.bindPopup(`$($jObject.Description.Name)$($jObject.Description.Blurb)

\n+ “气候:$($Climate)\n”+ “Stores:$($Stores)\n”+ “权限:$($jObject.Description.Authority)`;” 退回$out } $json='{“说明”:{ “身份证”:“布里泽霍姆镇”, “姓名”:“布里泽霍姆”, “宣传语”:“这座郊区宁静的小镇几乎繁荣起来 完全独立于周围的文明 近200年来,由于其巨大的财富积累 来自肥沃的农田、河流和航运业