使用PowerShell从OMDBAPI获取剧集季集信息时的格式转换错误
尝试获取剧集《Reacher》第1季第2集的数据,执行以下PowerShell代码时出现格式转换错误:
$Result = [xml] (Invoke-WebRequest "http://www.omdbapi.com/?Season=1&Episode=2&t=Reacher&apikey=$ApiKey")
报错信息:
Cannot convert value
"{"Title":"First Dance","Year":"2022","Rated":"TV-MA","Released":"04 Feb 2022","Season":"1",
"Episode":"2","Runtime":"52 min","Genre":"Action, Crime, Drama","Director":"Sam Hill",
"Writer":"Lee Child, Nick Santora, Scott Sullivan","Actors":"Alan Ritchson, Malcolm Goodwin,
Willa Fitzgerald",
"Plot":"When more victims are discovered,
Reacher attempts to get answers but is set up.
Roscoe discovers a threatening message.","Language":"English","Country":"N/A","Awards":"N/A",
"Poster":"https://m.media-amazon.com/images/M/MV5BMjYxOWZhZGEtMTRiMy00NWYzLWJmYjYtOTkxZDlkMGZmM2QxXkEyXkFqcG
deQXVyMTM3MTQxNzk@._V1_SX300.jpg",
"Ratings":[{"Source":"Internet Movie Database","Value":"8.1/10"}],"Metascore":"N/A", "imdbRating":"8.1","imdbVotes":"3639","imdbID":"tt14503476","seriesID":"tt928
8030","Type":"episode",
"Response":"True"}" to type "System.Xml.XmlDocument".Error: "The specified node cannot
be inserted as the valid child of this node, because the specified node is the wrong type."
At H:_mydocs\MovieCapture\Untitled19.ps1:5 char:1
$Result = [xml] (Invoke-WebRequest "http://www.omdbapi.com/?Season=1& ...
- CategoryInfo : InvalidArgument: (:) [], RuntimeException
- FullyQualifiedErrorId : InvalidCastToXmlDocument
OMDb API默认返回JSON格式数据,你试图将其强制转换为XML对象,这是错误的核心原因。改用JSON解析方式即可解决:
方法1:手动解析JSON
先获取响应内容,再用ConvertFrom-Json转换为PowerShell对象:
$response = Invoke-WebRequest "http://www.omdbapi.com/?Season=1&Episode=2&t=Reacher&apikey=$ApiKey" $result = $response.Content | ConvertFrom-Json
方法2:使用Invoke-RestMethod自动解析
Invoke-RestMethod会自动识别JSON响应并转换为PowerShell对象,写法更简洁:
$result = Invoke-RestMethod "http://www.omdbapi.com/?Season=1&Episode=2&t=Reacher&apikey=$ApiKey"
执行后,你可以通过$result.Title、$result.imdbRating等方式直接访问剧集的各项数据。
内容的提问来源于stack exchange,提问作者Paul

