[英]Convert XML to Json Angular
I am consuming an api that returns XML and am having trouble converting it to json, im trying to use the xml2js but i keep getting undefined in the console我正在使用返回 XML 的 api 并且在将其转换为 json 时遇到问题,我正在尝试使用 xml2js,但我一直在控制台中未定义
here is my api service这是我的 api 服务
export class WordgameService {
public apiUrl ="http://www.wordgamedictionary.com/api/v1/references/scrabble/";
public apiKey ="********************\";
constructor(private http: HttpClient) {
}
getSearchTerm(inputValue: string){
var xmlString = this.http.get(this.cors+this.apiUrl + inputValue+this.apiKey,{ responseType: 'text' , headers:{'Content-Type': 'application/xml'}}).subscribe(response => {
console.log(response);
});
var json = this.convertToJson(xmlString)
console.log(json)
return json;
console.log(json)
}
convertToJson(xml:any){
var json =xml2js.parseString(xml,function(err,result){
})
}
and the component和组件
export class WordCheckerComponent implements OnInit {
searchword = new FormControl('');
private results :any;
constructor(private apiService: WordgameService) {
}
searchWord() {
this.results = this.apiService.getSearchTerm(this.searchword.value);
}
ngOnInit(): void {
}
}
Also here is the response for the word "test"这里也是对“测试”这个词的回应
<entry>
<word>test</word>
<scrabble>1</scrabble>
<scrabblescore>4</scrabblescore>
<sowpods>1</sowpods>
<sowpodsscore>4</sowpodsscore>
<wwf>1</wwf>
<wwfscore>4</wwfscore>
</entry>
You can use xml-js to convert your XML response to JSON.您可以使用xml-js将您的 XML 响应转换为 JSON。 I found this to be simple and better than xml2js .
我发现这比xml2js简单且更好。 Also, make sure your console logging the JSON after the declaration and fetching from the correct API path.
此外,请确保您的控制台在声明后记录 JSON 并从正确的 API 路径获取。
This will be your XML response using xml-js这将是您使用 xml-js 的 XML 响应
var XMLResponse= this.http.get(this.cors+this.apiUrl + inputValue+this.apiKey,{ responseType: 'text' , headers:{'Content-Type': 'application/xml'}}).subscribe(response => {
console.log(response);
});
and this will be your JSON converted Response这将是您的 JSON 转换后的响应
var JSONResponse = JSON.parse(
convert.xml2json(XMLResponse, {
compact: true,
trim: true,
})
);
console.log(JSONResponse)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.