Angular JSON converter - Transform XML data to JSON format

Struggling to convert XML API response to JSON using xml2js library, facing issues with getting 'undefined' in the console. Here is my API service:

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;
}

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 {}
}

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>

View screenshot here

Answer №1

If you're looking to convert XML response to JSON, I recommend using the xml-js library. It provides a simple and effective way to handle this conversion compared to alternatives like xml2js. Remember to ensure that you are correctly logging the JSON data after fetching it from the API endpoint.

Below is an example of handling XML response with xml-js:

    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 here's how you can convert the XML response to JSON:

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

console.log(JSONResponse)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why does React / NextJS throw a "Cannot read properties of null" error?

In my NextJS application, I am using useState and useEffect to conditionally render a set of data tables: const [board,setBoard] = useState("AllTime"); const [AllTimeLeaderboardVisible, setAllTimeLeaderboardVisible] = useState(false); const [TrendingCreat ...

When running `npm install` and `ionic build`, not all node modules are installed

Currently facing some issues with node_modules while trying to build an existing Ionic app. Here is the package.json file: { "name": "My App", "private": true, "scripts": { "clean": "ionic-app-scripts clean", "build": "ionic-app-scripts buil ...

Best practice for translating a JSON file with extraneous data into a Java object

My Java application receives a large JSON string with nested data from a REST API response. I am using Jackson to map this JSON string to an object, but I only need about 50% of the information provided. How should I model the class that the JSON string wi ...

Tips for deleting on a numeric cell within ag-grid?

While exploring the functionality of AG-Grid with the example provided at this link [, I am currently experimenting with the numeric editor feature. I found this example on the official AG-Grid website [https://www.ag-grid.com/javascript-grid-cell-editor/ ...

What is the best way to display JSON data in a Listview control?

What is the best way to display JSON data in a list format? Currently, I am able to retrieve JSON data and display it in an alert dialog. The JSON data looks like this: [{"_id":"5449f20d88da65bb79a006e1","name":"name3","phone":"888888","service":"service ...

Limit choosing to group child elements within ag-grid

Is there a way to disable row selection in ag-grid specifically for the rows used to group the grid? For example, clicking on rows labeled with "United States" and "2008" should not trigger selection. Only rows like the one highlighted in blue should be se ...

Production is experiencing a hiccup, however, the site is still up and running. There seems to be

Having an error in production that I can't seem to replicate on my local machine. The error message reads: src/controllers/userController.ts(2,29): error TS2307: Cannot find module '../services/UserService' or its corresponding type declarat ...

Issues with NgRx testing - NullInjectorError: Service provider not found

When attempting to write unit tests for effects, I encountered the error NullInjectorError: No provider for StationsListService!. The code in my stations.effects.ts file looks like this: @Injectable() export class StationsListEffects { constructor(priva ...

Tabs on Ionic Page

I have a mobile app built with Ionic 3 and Angular that I am currently in the process of upgrading to Ionic 6. The app does not use tabs throughout, but certain pages within the app have tab functionalities. Here is a simplified example: foo.html: <io ...

Is it possible to simultaneously employ two asynchronous functions while handling two separate .json files?

Is it possible to work with 2 .json files simultaneously? My attempt did not succeed, so I am looking for an alternative method. If you have a suggestion or know the correct syntax to make this work, please share. And most importantly, does the second .j ...

Angular in production - ways to identify the packages being utilized (without utilizing npm)

I am facing a challenge with my production Linux environment, as I do not want to install npm or nodejs. The system currently hosts an asp.net core application and I need to verify if a specific package, postcss, is being used. During development, I notic ...

Strategies for transferring data from index.html to component.ts in Angular 4

Greetings, as a newcomer to Angular, I am seeking advice on how to link my Index.html file to component.ts. Please review the code snippet below where I have created a function called scannerOutput in my Angular index.html file which is functioning properl ...

having difficulties with angular subscribing to an observable

I am currently working on a service that retrieves a post from a JSON file containing an array of posts. I already have a service in place that uses HttpClient to return the contents of a JSON file. The main objective is to display the full content of the ...

What is the best way to group/merge multiple objects that have the same name into a single object (Nesting)?

I have a dataset containing students' names and their marks in different subjects stored as an array of objects. My goal is to merge the data into a single object for each student with matching names, resulting in one record per student. Here is an ex ...

Unable to access object key data from JSON-SERVER

I am currently attempting to send a GET request to json-server in order to retrieve data from a nested object. However, the response I am receiving is empty instead of containing the desired data key. After thoroughly reviewing the documentation, I could ...

Difficulty encountered while converting JSON strings to Java code

I am encountering an issue where I am trying to retrieve a string from an array within an object in a JSON array. Here is the snippet of my code: JSONArray deviceArray = new JSONArray(devicesJson); JSONObject obj1 = deviceArray.getJSONObject(0); System ...

I need assistance with utilizing the removeMarker function in GMaps.js to effectively sort and filter markers

Currently, I am using GMaps.js for my project. I have successfully added markers via JSON and now I'm looking to filter (hide) certain markers based on specific values within the JSON data. For instance, I want to hide all markers that do not have a v ...

Discover the power of Angular 4 with its *ngFor loop constraints, and enhance user interaction

<ul> <li *ngFor="let hero of heroes | slice:0:10;"> {{ hero.name }} </li> </ul> <p *ngIf="heroes.length > 10" (click)="showMore()">show more 10</p> I am looking to display additional hero names when clic ...

Transform PHP array into a properly structured array or object that can be easily used in JavaScript

My PHP code contains an array that looks like this: $variation = [ attribute_label => "Choose your Color", attribute_name => "pa_choose-your-color", variations => [ "819" => "Red", "820" => "Blue", ...

Error: TypeScript React SFC encountering issues with children props typing

I am currently working with a stateless functional component that is defined as follows: import { SFC } from "react"; type ProfileTabContentProps = { selected: boolean; }; const ProfileTabContent: SFC<ProfileTabContentProps> = ({ selected, child ...