I'm facing an issue when trying to convert a string to JSON in Ionic2

When attempting to retrieve json in the code below, an unexpected "space" is present after the opening brace and before the closing one:

{ 
  "address": ......,
  "filename": image.png,
  "price": 12
}

If I use res.json() in the following code, it results in a JSON parser error. However, if I utilize res.text(), it returns the string as expected. To address this issue, I attempted to remove the extra space by using replace.

this.http.get(Url)
 .map(res => res.text())
 .subscribe(data => {           
   JSON.stringify(data);        
     console.log(data.price);
 });

Ultimately, the console logs undefined instead of displaying the expected value of 12.

Upon switching back to using res.json(), the following error message appears: https://i.sstatic.net/RhSCk.png

Answer №1

The information in your JSON is stored within an object called data, which contains an array of objects:

{ "data": [{ "address":"124 Maple Street, Anytown, USA", "filename":"image3.png", "distance": 2878 , "price": 101001 }]}

If you attempt to access data.price through console log, it will not work. Instead, if you wish to display the price of the item within the array, you should use the following approach:

this.http.get(Url)
 .map(res => res.json().data) // extracting the array from the JSON
 .subscribe(data => {           
   console.log(data[0].price) // displaying the price of the first item in the array
 });

Answer №2

Here is a snippet of code I put together, although I must admit it doesn't look very elegant or visually appealing.

this.http.get(Url)
    .map(res => res.text())
        .subscribe(data => {            
          console.log(data);
          this.data=data;
          //these next two lines are crucial for the functionality
          this.data=this.data.replace(/\n/g,"");
          this.data=this.data.replace(/\t/g,"");
          console.log(this.data);

          //this.data=JSON.stringify(this.data);
          console.log(this.data);

          this.data=JSON.parse(this.data);
          console.log(this.data.data[0].price);
    });
  }

If you have any suggestions on improving the quality and appearance of this code, please feel free to share!

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

Refreshing the Ionic page by reloading it after navigating to a different URL page

Currently, I am working on an Ionic app where users can edit and view their profiles. After making changes on the edit profile page, the app should automatically navigate to the view profile page. My current issue is that I need the view profile page to r ...

Transforming XML responses into arrays

I am facing an issue where the XML response is successfully fetched in $response, but when I try to convert it into an array, it ends up being empty. How can I effectively convert this XML data into an array for display on a webpage? Any guidance or inform ...

Using an Android application to connect to an external database

I am currently working on integrating an external database (000webhost) into my app to fetch email addresses and display them in a ListView. While I am receiving the correct response from the server and can see it in the logcat, I am encountering a null po ...

Dealing with Promise Wrapper Already Declared in TypeScript Return TypeMismatch

Here is a snippet of TypeScript code I am working with: type Chain = 'eth' export type ApiMethods = { getToken: { path: 'tokens/' (args: { chain: Chain tokenAddress: EthereumAddress }): string } getRank: ...

Change the option in the dropdown menu from true/false to yes/no

Here is a snippet of code that I am working with: <div *ngSwitchCase="'Boolean'"> <select *ngIf="attribute.IsWritable" [(ngModel)]="animal[attribute.AttributeKey]"> <option (value)="animal[attribute.Attribut ...

Encountering issues with obtaining tokens silently using Angular and Microsoft MSAL, resulting in errors AADB2C90077 and AADB2C90205

Seeking assistance in retrieving a token from AAD B2C configuration using Angular9 and microsoft/msal My module setup is as follows; MsalModule.forRoot( { auth: { clientId: "xxxxxxxxxxxxxxxxx", ...

Verify the syntax and format of the POST body request using Node.js Express

Is there a way to verify the syntax of the POST request body received by my server on the '/route' route? I need to ensure: The body is in JSON format, The syntax is correct (no missing brackets or quotes). /// My Code /// app.use(express.jso ...

Tips for dynamically altering a template within an Angular application

My abstract component deals with rendering a tree. Is there a way to dynamically change the template for this component based on a condition? I believe the tree logic should be in a separate service. Would it make sense to create two components with diff ...

"Exploring the World of VS 2019 Community with an Exciting

After installing the latest version of Visual Studio Community and the newest Angular package, I added the angular project by selecting Add - New Project - "ASP.NET Core Web Application." ===== startup.cs { app.UseSpa(spa => { // To find out more ab ...

Developing unique custom methods in Django REST API for generic views

As an intern, I am currently working on a project that involves developing a DRF API to interact with a mobile app built by my colleague using the Ionic framework. Our task is to create new users, and here is the method in my view: class NewUser(generics. ...

Encountered an error: Object(...) function not defined when using React, Formik, and Webpack

I have encountered an issue while trying to use both Formik and React-Form-Hooks in my project. Despite using Typescript as my language and Babel as the transpiler, both libraries throw the same error when compiled. Uncaught TypeError: Object(...) is not ...

Step-by-step guide on discovering an object with an ID that is not present in a separate array

I have 2 arrays of objects. One array is the original array, and the other array contains the modified array. The modified array can include new objects, edited objects, or deleted objects in the settingValueDtoList. Currently, I am working on writing cod ...

Is there a way for me to convert a JBuilder view into a JSON string format?

I'm currently utilizing JBuilder to create JSON output on my project. The data is being generated by an index.json.jbuilder file, but I am facing a challenge when trying to convert it into a string format. Despite attempting methods like @my_object.to ...

In TypeScript, enhancing an interface with additional properties

Currently, I am working on an Angular project and have developed this interface to display some data: export interface UserData { name: string, vorname: string, strasse: string, plz: string, ort: string, handynummer: string, telefonnummer: s ...

How can I prevent double quotes from being automatically escaped within a JSON object?

update table set column = json_insert(column, '$.newKey', OUTPUT) I need help with inserting a JSON string value into the OUTPUT variable using the SQL query above. select json_object('key1', '{"key11": "value11&quo ...

Guide on executing a jar file using JavaScript and obtaining a JSON output

Is there a way to execute and capture the output of a jar file that returns a json using javascript? ...

What is the best way to add JavaScript sources to the startup.cs of AspNetCore?

Is there a simple way to link JS sources from a JS project located at "JSProj/src/main.js" and "JSProj/package.json" to execute in "AspNetCoreProj/startup.cs"? How can I ensure that when I run the ASP, my controller from &quo ...

A guide on effectively parsing a hefty JSON file with Python's ijson module

Currently, I am facing a challenge in parsing a massive JSON file (measuring hundreds of gigs) to extract data from its keys. To illustrate, let's take a look at the sample scenario below: import random, string # Generating a random key def random_ ...

Creating a MongoDB schema with python: A step-by-step guide

I am new to MongoDB and seeking assistance with creating JSON schemas in MongoDB using Python. I have three different JSON schemas that I would like to implement. Currently, my code looks like this: import pymongo client = pymongo.MongoClient("mongodb:// ...

Sliding toggle in Angular Material2 Menu

How can I properly include a Slide-toggle <mat-slide-toggle> within a Menu <mat-menu>? In addition, when I toggle the Slide-toggle, the menu closes. Is there a way to prevent this behavior? <mat-menu #menuSettings="matMenu"> ...