gpt4 book ai didi

javascript - 如何解析嵌入在http ://up-for-grabs.net/#/中的javascript变量数组?

转载 作者:行者123 更新时间:2023-11-28 00:20:28 24 4
gpt4 key购买 nike

我正在尝试解析http://up-for-grabs.net/#/使用 powershell 获取 CSV 文件中的内容。到目前为止我已经写了下面的代码

$URL = "http://up-for-grabs.net/#/"
$HTML = Invoke-WebRequest -Uri $URL
$script_blocks = $HTML.ParsedHtml.getElementsByTagName("script") | Where{ $_.type -eq ‘text/javascript’ }

$content = ""
foreach ($script_block in $script_blocks)
{
if($script_block.innerHTML -ne $null -and `
$script_block.innerHTML.trim().StartsWith("var files"))
{
$content = $script_block.innerHTML.trim()
}
}

进一步查看内容,它似乎是嵌入在 JavaScript 中的变量数组,其初始行的格式如下。它的数组没有空格或换行,这是我为了提高可读性而创建的。

<script type="text/javascript">
var files = {

"aspnet-razor-4":{"name":"ASP.NET Razor 4","desc":"Parser and code generator for CSHTML files used in view pages for MVC web apps.","site":"https://github.com/aspnet/Razor","tags":["Microsoft","ASP.NET","Razor","MVC"], "upforgrabs":{"name":"up-for-grabs","link":"https://github.com/aspnet/Razor/labels/up-for-grabs"}},

"fsharpdatadbpedia":{"name":"FSharp.Data.DbPedia","desc":"FSharp.Data.DbPedia - An F# type provider for DBpedia","site":"https://github.com/fsprojects/FSharp.Data.DbPedia","tags":[".NET","DbPedia","F#"],"upforgrabs":{"name":"up-for-grabs","link":"https://github.com/fsprojects/FSharp.Data.DbPedia/labels/up-for-grabs"}},

"makesharp":{"name":"Make#","desc":"Use C# scripts to automate the building process","site":"https://github.com/sapiens/MakeSharp","tags":[".Net","C#","make","build","automation","tools"],"upforgrabs":{"name":"up-for-grabs","link":"https://github.com/sapiens/MakeSharp/labels/up-for-grabs"}},

"stateprinter":{"name":"StatePrinter","desc":"Automating unittest asserts and ToString() coding.","site":"https://github.com/kbilsted/StatePrinter","tags":["TDD","Unit Testing","TDD",".NET","C#","ToString","Debugging"],"upforgrabs":{"name":"Help wanted","link":"https://github.com/kbilsted/StatePrinter/labels/Help%20wanted"}}

</script>

紧接着是

var projects = new Array();

for (var fileName in files) {
projects.push(files[fileName]);
}

如何在 powershell 中实现类似的快速解析,而无需使用字符串标记化编写大量代码。

最佳答案

经过一番研究,我发现这是一个 JSON 内容,powershell cmdlet ConvertFrom-Json需要使用。我不想在这里复制整个脚本。请看this GitHub location了解如何有效地使用此 cmdlet。基本上,您需要记住此 cmdlet 返回的对象是一个自定义对象,需要枚举它才能获取各种属性。它不是一个数组,因此只有 foreach 才能揭示内容。下面是一个小代码示例

$file_json = $file_string | ConvertFrom-Json
$delim = " ; "

foreach ($item in $file_json | gm)
{
$props = $file_json.$($item.Name)
if($props.MemberType) {continue}

$row = $props.name.ToString()
$row += $delim + $props.desc.ToString()
$row += $delim + $props.site.ToString()
}

在网络上搜索此 cmdlet 将为您提供有关如何处理此转换的更多详细信息。

关于javascript - 如何解析嵌入在http ://up-for-grabs.net/#/中的javascript变量数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30079274/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com