Bucle a través de un archivo JSON en PowerShell
El objetivo principal de este artículo es demostrar cómo realizar un bucle e iterar a través de un archivo JSON en secuencias de comandos de PowerShell.
Bucle de PowerShell a través de JSON
Al tratar con objetos JSON durante la creación de secuencias de comandos en PowerShell, puede ocurrir que para acceder a una determinada propiedad, es posible que desee iterar a través de ella.
Considere el siguiente objeto JSON:
[
{
"id": 1,
"first_name": "Twila",
"last_name": "Witcherley",
"email": "twitcherley0@issuu.com",
"gender": "Female",
"ip_address": "129.230.255.192"
}, {
"id": 2,
"first_name": "Rafaelita",
"last_name": "Fearnehough",
"email": "rfearnehough1@nsw.gov.au",
"gender": "Polygender",
"ip_address": "247.204.187.100"
}, {
"id": 3,
"first_name": "Eimile",
"last_name": "Denyer",
"email": "edenyer2@nps.gov",
"gender": "Female",
"ip_address": "125.244.213.155"
}, {
"id": 4,
"first_name": "Sly",
"last_name": "Conman",
"email": "sconman3@meetup.com",
"gender": "Polygender",
"ip_address": "194.50.217.42"
}, {
"id": 5,
"first_name": "Augustine",
"last_name": "Ciccotti",
"email": "aciccotti4@google.ca",
"gender": "Male",
"ip_address": "192.158.101.100"
}
]
En el contexto del JSON mencionado anteriormente, puede ser necesario acceder a id
, first_name
, last_name
, email
, sexo
y ip_address
.
Utilice ConvertirDe-Json
La solución se puede resolver de dos formas, principalmente en base a la versión de PowerShell.
Considere el siguiente fragmento:
$j =
@'
[{"id":1,"first_name":"Twila","last_name":"Witcherley","email":"twitcherley0@issuu.com","gender":"Female","ip_address":"129.230.255.192"},{"id":2,"first_name":"Rafaelita","last_name":"Fearnehough","email":"rfearnehough1@nsw.gov.au","gender":"Polygender","ip_address":"247.204.187.100"},{"id":3,"first_name":"Eimile","last_name":"Denyer","email":"edenyer2@nps.gov","gender":"Female","ip_address":"125.244.213.155"},{"id":4,"first_name":"Sly","last_name":"Conman","email":"sconman3@meetup.com","gender":"Polygender","ip_address":"194.50.217.42"},{"id":5,"first_name":"Augustine","last_name":"Ciccotti","email":"aciccotti4@google.ca","gender":"Male","ip_address":"192.158.101.100"}]
'@
foreach ($record in ($j | ConvertFrom-Json))
{
write-host "$($record.id) | $($record.first_name) | $($record.last_name) | $($record.email) | $($record.gender) | $($record.ip_address)"
}
Lo que da la siguiente salida:
1 | Twila | Witcherley | twitcherley0@issuu.com | Female | 129.230.255.192
2 | Rafaelita | Fearnehough | rfearnehough1@nsw.gov.au | Polygender | 247.204.187.100
3 | Eimile | Denyer | edenyer2@nps.gov | Female | 125.244.213.155
4 | Sly | Conman | sconman3@meetup.com | Polygender | 194.50.217.42
5 | Augustine | Ciccotti | aciccotti4@google.ca | Male | 192.158.101.100
Podemos usar el cmdlet ConvertFrom-Json
para convertir una cadena JSON en una estructura de datos de PowerShell.
La razón para usar ConvertFrom-JSON
es que PowerShell no admite la iteración sobre objetos JSON sin convertirlos primero en algo adecuado. En este caso, ConvertFrom-Json
se usa para convertir la cadena JSON en un PSCustomObject
, con cada una de sus propiedades representando un campo JSON.
Usar objeto deserializar
Considere el siguiente fragmento:
Add-Type -AssemblyName System.Web.Extensions
$JS = New-Object System.Web.Script.Serialization.JavaScriptSerializer
$j =
@'
[{"id":1,"first_name":"Twila","last_name":"Witcherley","email":"twitcherley0@issuu.com","gender":"Female","ip_address":"129.230.255.192"},{"id":2,"first_name":"Rafaelita","last_name":"Fearnehough","email":"rfearnehough1@nsw.gov.au","gender":"Polygender","ip_address":"247.204.187.100"},{"id":3,"first_name":"Eimile","last_name":"Denyer","email":"edenyer2@nps.gov","gender":"Female","ip_address":"125.244.213.155"},{"id":4,"first_name":"Sly","last_name":"Conman","email":"sconman3@meetup.com","gender":"Polygender","ip_address":"194.50.217.42"},{"id":5,"first_name":"Augustine","last_name":"Ciccotti","email":"aciccotti4@google.ca","gender":"Male","ip_address":"192.158.101.100"}]
'@
$data = $JS.DeserializeObject($j)
$data.GetEnumerator() | foreach-Object {
foreach ($key in $_.Keys)
{
Write-Host "$key : $($_[$key])"
}
}
Producción :
id : 1
first_name : Twila
last_name : Witcherley
email : twitcherley0@issuu.com
gender : Female
ip_address : 129.230.255.192
id : 2
first_name : Rafaelita
last_name : Fearnehough
email : rfearnehough1@nsw.gov.au
gender : Polygender
ip_address : 247.204.187.100
id : 3
first_name : Eimile
last_name : Denyer
email : edenyer2@nps.gov
gender : Female
ip_address : 125.244.213.155
id : 4
first_name : Sly
last_name : Conman
email : sconman3@meetup.com
gender : Polygender
ip_address : 194.50.217.42
id : 5
first_name : Augustine
last_name : Ciccotti
email : aciccotti4@google.ca
gender : Male
ip_address : 192.158.101.100
Para superar este problema, podemos usar .NET JavaScriptSerializer
para manejar nuestro archivo JSON. Como el JavaScriptSerializer
devuelve un Diccionario
, la iteración es relativamente sencilla utilizando los métodos GetEnumerator()
y foreach-Object
.
Recuerde que se requiere PowerShell 2.0 y .NET Framework 2 - 4.8
para hacer referencia a la dll System.Web.UI.WebResourceAttribute
.
Hello! I am Salman Bin Mehmood(Baum), a software developer and I help organizations, address complex problems. My expertise lies within back-end, data science and machine learning. I am a lifelong learner, currently working on metaverse, and enrolled in a course building an AI application with python. I love solving problems and developing bug-free software for people. I write content related to python and hot Technologies.
LinkedIn