Converting JSON to an array in Ionic 3

I'm struggling to convert a JSON response from a Laravel API into an array in my Ionic 3 app.

Below is the JSON structure:

https://i.sstatic.net/izRAV.png


Object {
    id_oiseau: 1, 
    nom_commun: "Hirondelle", 
    lieu_signalement: "Foret", 
    date_signalement: "2017-05-16", 
    condition_signalement: "Aile coincee sous branche",
    date_reception:"2017-05-16",
    date_renvoi:"2017-05-02",
    and more...
}

I have created a provider to fetch this JSON data for my Ionic app:


export class BirdService {

    returnedData;
    headers: any;
    options: any;

    constructor(public http: Http) {
        this.headers = new Headers();
        this.headers.append('Content-Type', 'application/json');
    }

    getRemoteData(): Observable<any> {
        return this.http.get('http://extranet.local/api/v1/bird/1', this.headers).map(res => res.json());
    }
}

And here is the function I'm using to convert the JSON:


export class HistoryPage {

    constructor(public navCtrl: NavController, public serviceOne: BirdService) {}

    ionViewDidLoad() {

        this.serviceOne.getRemoteData().subscribe(
            data => {
                let list: History[] = data;
                console.log(data);
        });
    }
}

However, I am facing issues as the JSON file remains in its original JSON format. I tried using parseJSON with jQuery but encountered an error stating "Cannot read property 'parseJSON' of undefined". I also attempted to use Angular's fromJson method, but Ionic couldn't recognize the name "angular". Any suggestions on how to resolve this issue would be greatly appreciated!

Answer №1

Utilize the JSON.parse() function to parse the data.

No additional library imports are necessary for this parsing task.

Your code implementation should resemble the following:

ionViewDidLoad() {

        this.serviceOne.getRemoteData().subscribe(
            data => {
                var Results = JSON.parse(data);
                console.log(Results);
        });
    }

Answer №2

There is no need to manually parse the json within the subscribe method. Rather, you are already handling it within the map function. Using map(res => res.json())


             let list: History[] = data;

The issue lies in the fact that your data is an object and not an array.

To resolve this, simply use:


       var history = data;

You can access the content of the object like this:

 
  console.log(history.nom_commun); 

Answer №3

Thank you once more, but I have discovered a different solution,

I implemented the following code snippet:

History.push(data);

By adding the data to an object within an array, my system in conjunction with Angular seems to be functioning smoothly with this method.

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

The global function is not recognized within the Angular controller script

I am facing an issue with calling a global function within an Angular controller. Here is the scenario: initiateCheckList = {}; $(function() { initiateCheckList = function() { ... } Inside an Angular controller, I have a function that tries ...

Has anyone created a modified version of jRails that is compatible with Rails 2.3 and jQuery 1.4?

We are revamping a website with Rails, and the current site heavily relies on jQuery v1.4 in its templates. We want to ensure that the existing scripts continue to function while also utilizing Rails' javascript helpers for our new scripts. While jRai ...

Convert this text into HTML code: "Textarea to

I have a basic <textarea> element that I want to transform links (www.google.com, msn.com, etc) and line breaks (\r\n) into HTML code. I found one library for converting links into <a hrefs>. Another library can convert line breaks i ...

Transfer all HTML variables using AJAX with jQuery

Is it possible to pass all HTML tag values to another file using AJAX? $.ajax({ url:"myp.php", type:'POST', data: //here I want to include all possible element values in the current HTML document }); Any suggestions or ideas on how to ...

Issues with launching NPM Start (Having trouble with Node on Mac OS X Yosemite)

As a Rails developer, I decided to expand my skills by learning Angular JS. I came across this tutorial that seemed interesting, but I'm stuck at trying to get a node server to run. Here is the content of the npm-debug.log file: 0 info it worked if ...

Flexible type definition including omission and [key:string]: unknown

When I write code, I like to explain it afterwards: type ExampleType = { a: string; b: boolean; c: () => any; d?: boolean; e?: () => any; [inheritsProps: string]: unknown; // If this ^ line over is removed, TypeNoC would work as expecte ...

Neglecting to validate types in the personalized response format within Express

I'm new to typescript and I've run into a problem where I can't seem to get my types validated. Route app.use((req: Request, res: Response) => { // here 404 is a string but should be a number according to type defined but no error is s ...

Attempting to incorporate the jquery-mousewheel plugin into the jquery cycle2 library

I've been working on integrating the jquery-mousewheel plugin (https://github.com/jquery/jquery-mousewheel) with the jquery cycle2 plugin. Initially, everything was running smoothly until I encountered an issue where mouse scrolling was generating ex ...

Validation of forms can be achieved through the use of System.ComponentModel.DataAnnotations along with

I have developed a C# ASP.NET MVC web application where I am implementing form validation using System.ComponentModel.DataAnnotations. An example of how I validate a password field is shown below: [Required] [StringLength(100, ErrorMessage = "The {0} mus ...

Convert a regular element into a DebugElement within an Angular framework

Recently, I was working on testing an Angular Component which was going smoothly until I encountered a challenging issue that has been perplexing me for days. My main objective was to test whether the method "ajouterCompteurALaCampagne" is being called whe ...

Is there a way to modify the title of a website upon entering the webpage and then updating it when moving to a new page?

I'm encountering an issue with changing the website title during two specific processes. Upon entering a webpage, the title is modified using the following code: <script type="text/javascript"> $(document).ready(function() { docum ...

Compiling and rendering HTML code from a file with AngularJS

Here is the custom directive code that I have created: angular.module('app.directives', []).directive('userHeader', ['authService', '$compile', function(authService, $compile) { return { restrict: 'AEC&ap ...

Finding all parent IDs from a given child ID within a nested JSON structure that contains children can be achieved by recursively

function loadKendoTreeView() { if ($("#treeview").data("kendoTreeView") != null) { $("#treeview").data("kendoTreeView").destroy(); $("#treeview").empty(); } var jsonData = [{ "Id": "239297d8-5993-42c0-a6ca-38dac2d8bf9f", ...

The calendar on the Datetimepicker is not appearing in the proper position

I have encountered an issue while using Eonasdan bootstrap datetimepicker in a paramquery grid. Whenever I open the datetimepicker, the calendar appears hidden inside the grid. To tackle this problem, I added the following CSS condition: .dr ...

Enhance jQuery event handling by adding a new event handler to an existing click event

I have a pre-defined click event that I need to add another handler to. Is it possible to append an additional event handler without modifying the existing code? Can I simply attach another event handler to the current click event? This is how the click ...

Tips on how to customize an Ajax modal appearance

I need to customize the CSS styling of a modal for editing purposes. Can anyone provide guidance on how to set the width, height, and other properties using the code snippet below? // Open modal in AJAX callback $("modal").dialog({ modal: true, minH ...

I am looking for an image search API that supports JSONP so that users can easily search for images on my website

I am currently in the process of creating a blog platform. My goal is to allow users to input keywords on my site and search for images directly within the website. This way, I can easily retrieve the URL of the desired image. ...

Global AngularJS service

I am attempting to save a response variable in a global service variable. Here is my service: (function() { angular.module('employeeApp') .service('constants', constants); function constants() { this.url = &apo ...

Utilize jQuery to showcase images on your webpage

There seems to be an issue with image display - sometimes the selected image does not show up until clicked a second time. Using jQuery $('#morefiles').change(function (event) { if (!(/\.(gif|jpg|jpeg|tiff|png)$/i).test($(this).val())) { ...

Notify programmers about the potential risks associated with utilizing certain third-party components

Incorporating a 3rd party library into our codebase involves utilizing its components directly, although some are enclosed within internally created components. Is there a method available to alert developers when they try to use one of the wrapped compone ...