将XML转换为Json

将XML转换为Json,json,angular,xml,typescript,Json,Angular,Xml,Typescript,我正在使用一个返回XML的api,并且在将其转换为json时遇到困难,我试图使用xml2js,但我在控制台中一直没有定义 这是我的api服务 export class WordgameService { public apiUrl ="http://www.wordgamedictionary.com/api/v1/references/scrabble/"; public apiKey ="********************\"; cons

我正在使用一个返回XML的api,并且在将其转换为json时遇到困难,我试图使用xml2js,但我在控制台中一直没有定义

这是我的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){
})

}
 

    
   
以及组件

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 {


  }
}
下面是对“测试”一词的回答


测试
1.
4.
1.
4.
1.
4.
您可以使用 将XML响应转换为JSON。我发现这很简单,而且比以前更好。另外,确保控制台在声明之后记录JSON并从正确的API路径获取

这将是使用XMLJS的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);
});
这将是您的JSON转换响应

var JSONResponse = JSON.parse(
      convert.xml2json(XMLResponse, {
        compact: true,
        trim: true,
      })
    );

console.log(JSONResponse)

您尝试转换响应的代码在哪里?很抱歉,在postingIv尝试使用xml2js之前,我把它取出来了,但我一直没有定义?您需要将var json=this.convertToJson(xmlString)console.log(json)放在subscribe中。我刚刚完成了,但是我得到了一个订户对象?我在问题中发布了一个图像
var JSONResponse = JSON.parse(
      convert.xml2json(XMLResponse, {
        compact: true,
        trim: true,
      })
    );

console.log(JSONResponse)