【问题标题】:Print data from JSONs using Powershell使用 Powershell 从 JSON 打印数据
【发布时间】:2018-11-10 01:36:15
【问题描述】:

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

多个单独的 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 `);

但每一个都有几百次。我想要的只是我可以复制并粘贴到我现有的 html 文件中,这样我就不必自己为每个位置写出上述内容。

您可以忽略坐标,我不想要该信息并且我不需要标记数组,我将自己放入标记数组,因为它们的坐标与标记数组不同。

【问题讨论】:

  • 哪个部分是powershell?
  • 如果我是你,我会忘记 powershell。在您的网络服务器上上传 json 文件,并使用 ajax 请求(我推荐 axios)来获取它们。类似于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(`&lt;h1&gt;${response.data.Description.Name}&lt;/h1&gt;`); 的东西(不完整,但我想你明白了。)'` jQuery 也有一个 [.get()] 如果它更熟悉的话。同样的事情(jquery 做了 1000 件事情,axios 只做 ajax 请求)。
  • 我只知道 powershell 将是提取此类信息的绝佳候选者,因为我过去使用过类似的查询功能,但仅适用于单点数据。任何可以做到的都可以,我只知道 powershell 能够做到并且非常常用。我想要powershell做的就是读取json,并打印出信息,但不仅仅是给我每个位置及其信息的列表,而是在我放入的示例js代码中插入相关点到需要它们的位置操作
  • 感谢 ippi,但我根本不想做。我不希望不断查询服务器上的 350 个 json。它们包含完成我想做的任务所需的数据的 100 倍。我只需要示例中列出的数据,而不需要 350 个 json 中的 3-600 行文本。我知道我要问的对powershell来说很简单,而且可以做到,我过去看过其他人的最终结果,只是不知道该怎么做。另外,您似乎错过了整点。使用您的示例,我仍然需要为每个标记输入该代码,powershell 可以打印该信息并将其粘贴到我的 html
  • 好吧,我明白你的意思了,我在阅读有关 powershell 和 convertTo-json 时学到了一两件事。只是说,javascript 和 json 就像面包和黄油。 Powershell 显然是这里的开销。我可以建议一个节点脚本吗? (对不起!)

标签: javascript json powershell


【解决方案1】:

在其他地方几分钟内就可以定制我的答案。还是谢谢

##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
}

【讨论】:

  • 知识是要分享的,而不是囤积的!希望它会在未来对其他人有所帮助
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    然后我将分享我的节点解决方案,没有人要求,但我认为这将是一个很好的练习。

    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 解决方案。吸取了教训。非常有趣。

    【讨论】:

    • 谢谢,将获得可接受的结果。但是再次设置需要输入数百个单独的参数,以便它知道从什么调用,我列出的答案会自动从每个单独的 json 中读取,而无需知道它们的名称。不过感谢您的输入,将其保存以备日后使用!
    • 啊哈,我认为这是只提取您想要的数据的要求。但是,是的,你现在需要一个 babel 插件来支持节点中的import * from './folder'
    • 是的,这个脚本不适合 JS,它用于在 powershell 中读取 jsons 并返回一个可以直接转储到文件中的完全工作的 JS 代码。一个自动搜索所有文件夹和文件并将所有数据汇集到工作代码中的脚本。这正是我的 powershell 主要人员在下面为我所做的
    • 我不否认我挑选了三个文件,(但你可以通过jsonGlob('**/*.json') 或 babel-wildcard import * from '../somefolder' 获得所有文件)。但再一次,我还必须坚持这个节点脚本确实从你想要的任何文件夹中读取 jsons 并输出一个完全工作的 javascript 文件。
    • 最重要的是,我不否认没有人想要一个节点解决方案,所以这一点没有实际意义。
    猜你喜欢
    • 2017-12-27
    • 1970-01-01
    • 2018-07-03
    • 2017-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    相关资源
    最近更新 更多