使用POWERSHELL将JSON文件转换为XML文件
我需要将Json文件从web转换为xml文件,我需要非常简单的方法。。。我需要Json响应中的几个数据。。。 周围有很多,但不是很清楚。 我发现了一些这样的样本:使用POWERSHELL将JSON文件转换为XML文件,json,xml,powershell,Json,Xml,Powershell,我需要将Json文件从web转换为xml文件,我需要非常简单的方法。。。我需要Json响应中的几个数据。。。 周围有很多,但不是很清楚。 我发现了一些这样的样本: PS c:\0> ConvertTo-Xml -InputObject temp_JSON.json -As String PS c:\0> ConvertTo-Xml -InputObject temp_JSON.json -As document 但我看不到或找不到结果。。。我错了 这是要转换的Json响应字
PS c:\0> ConvertTo-Xml -InputObject temp_JSON.json -As String
PS c:\0> ConvertTo-Xml -InputObject temp_JSON.json -As document
但我看不到或找不到结果。。。我错了
这是要转换的Json响应字符串:
"{"data":[{"id":"86xEyb****lUsw==","custom_fields":{"firstName":"Z***n","lastName":"Pe***ki","locale":"EN-GB_MK","timezone":"8","gender":"N\/A","phone":"+38***6","email":null},"tags":[],"created_at":1600276472}],"links":{"first":"http:\/\/app.respond.io\/api\/v1\/contact\/by_custom_field?name=firstName&value=zoran&page=1","last":"http:\/\/app.respond.io\/api\/v1\/contact\/by_custom_field?name=firstName&value=zoran&page=1","prev":null,"next":null},"meta":{"current_page":1,"from":1,"last_page":1,"path":"http:\/\/app.respond.io\/api\/v1\/contact\/by_custom_field","per_page":10,"to":1,"total":1}}"
@Guenther Schmitz的答案非常完美,
但我还需要一些关于xml风格的问题。我收到的输出像
<Objects>
<Object Type="System.Management.Automation.PSCustomObject">
<Property Name="data" Type="System.Object[]">
<Property Type="System.Management.Automation.PSCustomObject">
<Property Name="id" Type="System.String">*******</Property>
<Property Name="custom_fields" Type="System.Management.Automation.PSCustomObject">
<Property Name="firstName" Type="System.String">B***</Property>
<Property Name="lastName" Type="System.String">B***</Property> ...
但仍然存在:您首先必须将json文件转换为类似的PowerShell对象
$JsonObject = Get-Content -Path "C:\path\to\temp_JSON.json" | ConvertFrom-Json
然后可用于参数InputObject
$XML = ConvertTo-Xml -As Stream -InputObject $JsonObject -Depth 3
请注意参数深度
。您可能需要根据您的结构来处理这个问题,因为默认值为1。有关参考信息,请参阅
然后,可以使用命令Out file
Out-File -FilePath "C:\path\to\temp_XML.xml" -InputObject $XML
这也可以通过管道在一条管线中完成
Get-Content -Path "C:\path\to\temp_JSON.json" | ConvertFrom-Json | ConvertTo-Xml -As Stream -Depth 3 | Out-File -FilePath "C:\path\to\temp_XML.xml"
谢谢@Guenther Schmitz,这是向前迈出的一步,我需要这样。我在PS控制台中尝试了line,但不幸的是,它是创建的空文件xml,在xml对象内部没有任何数据-------version=“1.0”encoding=“utf-8”ObjectsPS C:\>Get Content-Path“C:\0\temp\u JSON.JSON”| ConvertFrom JSON | ConvertTo Xml-As Document-Depth 3 | Out File-FilePath“C:\0\temp\u Xml.Xml”我用这个,我错了吗?JSON的内容是什么?你们能把这个添加到你们的问题中吗?我在主要问题中添加了json字符串,若我从浏览器中打开json文件显示正确的话
$XML = ConvertTo-Xml -As Stream -InputObject $JsonObject -Depth 3
Out-File -FilePath "C:\path\to\temp_XML.xml" -InputObject $XML
Get-Content -Path "C:\path\to\temp_JSON.json" | ConvertFrom-Json | ConvertTo-Xml -As Stream -Depth 3 | Out-File -FilePath "C:\path\to\temp_XML.xml"