You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell创建PSCustomObject及生成指定格式JSON Payload技术求助

PowerShell: Generate Target JSON Payload from ID File

Hey there! Let's tackle this PowerShell JSON payload problem together. Here's a straightforward, reliable way to build exactly the JSON structure you need from your ID file.

Step-by-Step Solution

First, let's assume your ID file has one ID per line (the most common format for this scenario). If your file uses a different delimiter, I'll add a quick tweak for that too.

1. Full Working Code

# 1. Read the ID file, filter out empty lines to avoid invalid entries in the array
$assetIds = Get-Content -Path "C:\your\file\path\ids.txt" | Where-Object { $_ -match '\S' }

# 2. Build the custom object matching your target JSON structure
$jsonPayload = [PSCustomObject]@{
    assetIds = $assetIds
    sendNotification = $true
}

# 3. Convert to properly formatted JSON (use -Compress if you want minified output)
$jsonPayload | ConvertTo-Json -Depth 10

# Optional: Save directly to a JSON file
# $jsonPayload | ConvertTo-Json -Depth 10 | Set-Content -Path "C:\your\output\payload.json"

2. Key Details Explained

  • Filtering Empty Lines: The Where-Object { $_ -match '\S' } ensures we skip any blank lines in your ID file, so your assetIds array won't have empty strings.
  • PSCustomObject Structure: Using [PSCustomObject] creates an object with exactly the keys your target JSON requires (assetIds and sendNotification), which translates perfectly when converted to JSON.
  • Depth Parameter: -Depth 10 ensures PowerShell properly serializes the array (the default depth is 2, which works here, but setting a higher value prevents issues if you ever expand the structure later).
  • Minified vs. Pretty-Print: Remove -Depth 10 and add -Compress if you need minified JSON instead of human-readable format.

3. If Your IDs Are Comma-Separated (Not Per Line)

If your ID file has all IDs in a single line separated by commas (e.g., id1, id2, id3), adjust the first line to split and clean the values:

$assetIds = (Get-Content -Path "C:\your\file\path\ids.txt" -Raw).Split(',') | ForEach-Object { $_.Trim() } | Where-Object { $_ }

That should give you exactly the JSON payload you're targeting! Let me know if you run into any edge cases with your specific ID file format.

内容的提问来源于stack exchange,提问作者Hein

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 18:42:53