【问题标题】:Convert XML to Json Angular将 XML 转换为 Json Angular
【发布时间】:2021-01-16 20:52:58
【问题描述】:

我正在使用一个返回 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 {


  }
}

这里也是对“测试”这个词的回应

<entry>
    <word>test</word>
    <scrabble>1</scrabble>
    <scrabblescore>4</scrabblescore>
    <sowpods>1</sowpods>
    <sowpodsscore>4</sowpodsscore>
    <wwf>1</wwf>
    <wwfscore>4</wwfscore>
</entry>

enter image description here

【问题讨论】:

  • 您尝试转换响应的代码在哪里......?
  • 对不起,我在发帖前把它拿出来了
  • 我尝试使用 xml2js 但我一直不确定?
  • 你需要把 var json = this.convertToJson(xmlString) console.log(json) 放在订阅里面..
  • iv 刚刚完成,但我得到了一个订阅者对象?,我在问题中发布了一张图片

标签: json angular xml typescript


【解决方案1】:

您可以使用xml-js 将您的 XML 响应转换为 JSON。我发现这比xml2js 简单而且更好。此外,请确保您的控制台在声明后记录 JSON 并从正确的 API 路径获取。

这将是您使用 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);
});

这将是您的 JSON 转换响应

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

console.log(JSONResponse)

【讨论】:

    猜你喜欢
    • 2017-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-09
    • 1970-01-01
    • 2015-05-30
    相关资源
    最近更新 更多