Splitting each column in JavaScript using JSON.parse

While working on a JavaScript scraper for parsing JSON data, I encountered the challenge of separating each column with a value and data. After trying several methods, my code ended up looking like this:


searchMangaFromElement(element) {
    var obj = JSON.parse(element.text())
    var name = obj.suggestions.map(user => user.value);
    var url = obj.suggestions.map(user => user.data);
    var thumbnail = `${this.baseUrl}/uploads/manga/${url}/cover/cover_250x350.jpg`
    var rank = '0';
    return super.manga(name, url, thumbnail, rank);
}

{
  "mangas": [
    {
      "name": [...list of manga names...],
      "url": [...list of URLs...],
      "thumbnail": "https://zahard.xyz/uploads/manga/th3-b0xer,7854-im-the-grim-reaper,th3-girl-d0wnstairs,...",
      "rank": "0"
    }
  ],
  "hasNextPage": 1,
  "nextPage": 1,
  "results": 1
}

I then attempted to improve the code by iterating through the suggestions object in the JSON data:


searchMangaFromElement(element) {
    var obj = JSON.parse(element.text())
    for (var vals in obj.suggestions) {
        var url = obj.suggestions[vals].data;
        var name = obj.suggestions[vals].value;
        var thumbnail = `${this.baseUrl}/uploads/manga/${url}/cover/cover_250x350.jpg`
        var rank = '0';
        return super.manga(name, url, thumbnail, rank);
    }
}

Furthermore, an alternative method using Cheerio library was implemented to parse specific content as shown below:


{
  "mangas": [
    {
      "name": "10 Years in the Friend Zone",
      "url": "/manga/2053/10-years-in-the-friend-zone",
      "thumbnail": "https://cdn.mangaworld.in/mangas/5faa0b5f66d2cb714b2b2df9.png?1640316529137?",
      "rank": "0"
    },
    {...more manga entries...}
  ],
  "hasNextPage": true,
  "nextPage": 2,
  "results": 16
}

Answer №1

Give this code a shot

fetchMangaFromElement(element) {
    const data = JSON.parse(element.text())
    const mangaList = [] // initializing an array
    for (var item in data.results) {
        var url = data.results[item].link;
        var title = data.results[item].title;
        var coverImage = `${this.websiteUrl}/images/${url}/cover/cover_300x400.png`
        var rating = '5';
        // add each item to the manga list
        mangaList.push({title, url, coverImage, rating})
    }

    console.log('mangaList:', mangaList)
    
    // set it as super.manga
    return super.manga(mangaList);
}

If there are any issues, demonstrate the functionality of super.manga

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

Struggling to deserialize JSON information into a Dictionary with key and value pairs of strings

Looking to convert this JSON data into a Dictionary using native Javascript. var jsonData = "{"Symptom":[true,true,true],"Action":[true,true],"AllArea":true}"; However, encountering an error when trying to deserialize it with the following code: Diction ...

Creating various arrays of JSON objects using JavaScript

I have a pre-existing array set up like this. var dataLayer = []; dataLayer = [{ 'transactionProducts': [{ 'sku': '96710381', 'name': 'QEH', 'category': 'GLD', 'price': ' ...

Following an AJAX request, jQuery.each() does not have access to the newly loaded CSS selectors

Note: While I value the opinions of others, I don't believe this issue is a duplicate based on the provided link. I have searched for a solution but have not found one that addresses my specific problem. Objective: Load HTML content to an element u ...

Incorporating Common Types for Multiple Uses

Is there a way to efficiently store and reuse typings for multiple React components that share the same props? Consider the following: before: import * as React from 'react'; interface AnotherButtonProps { disabled?: boolean; onClick: (ev ...

Microsoft Edge breaks free: Introducing Dark Mode for iOS

It seems like Microsoft Edge's "Dark Mode" on iOS has a mind of its own. While it works as expected on Chrome, Safari, Firefox (iOS), and Chrome, Safari, Firefox, and Edge (OSX/Windows), I'm encountering some issues specifically with Edge on iOS. ...

Utilizing a Function's Return Value as a State in React - A Comprehensive Guide

Currently, I am delving into the realm of functional components within React and have crafted a simple piece of code that should output 'Nah' if the state value is at 0. However, there seems to be an issue as this functionality does not seem to ...

Utilize the v-if directive within a v-for loop

I am currently iterating over an array named cars using the v-for directive. I would like to implement a condition within this loop so that if the color property matches a certain value, a specific CSS style is applied. <p v-for="car in cars" ...

What is the method for utilizing a filter to extract the specific value from the elements within an array of double objects?

I am facing an issue with my code where I have an array called pick containing objects and another object named diaryItem. My goal is to extract only the object with the name 'wormColor' from the diaryItem object. Unfortunately, when I tried run ...

Exploring Quadrics with Marching Cubes in Three.js

I have been attempting to create an applet that displays various types of space quadrics using the Marching Cubes library from three.js to render implicit surfaces. However, the shapes that are being generated do not appear as expected, leading me to belie ...

Selecting a video at random from the YouTube API JSON Response in PHP

Imagine conducting a simple YouTube search through the YouTube API v3 and receiving a response with various video results. How can you randomize these results and select only one item from the entire response? While functions like shuffle() and array_rand ...

What is the best way to combine duplicate JSON objects together?

I am facing a challenge with my json data structure, shown below: [{ "attributeId": 6, "attributeType": "price", "attributeValue": "{10,20,100}", "displayOn": "true", "attributeName": "price" }, { "attributeId": 6, "attribu ...

What is the best way to implement conditional hook usage in React?

Having two hooks at my disposal, useLocalStorage and useQuery, I find myself wondering about conditionally utilizing one of them based on an input prop. I'm considering writing the following: const [value, setValue] = localStorage ? useLocalStorage() ...

Caution when using a React form: Value of `true` has been detected for a non-boolean attribute `validate`

I am trying to address a warning message that I have received index.js:1 Warning: Received true for a non-boolean attribute validate. If you want to write it to the DOM, pass a string instead: validate="true" or validate={value.toString()}. I ...

Store JSON data in a Python variable

I need to store data from a Json file into separate variables so that I can use them for other purposes. I have successfully created a Json file from inputs in another QDialog. Now, my goal is to extract the inputs from the Json file and assign them to ind ...

How can I prevent the <br/> tag from being included on every new line when exporting data to PDF in jQuery Datatable?

I am currently working with a datatable that contains a large amount of data. Within this table, I have included 2 buttons for exporting the data in PDF and CSV formats. One of the columns within my table contains a comma-separated string, and when I expor ...

Can the PDF document be set to print instead of the webpage?

As a junior developer, my current project involves creating a resume on github.io that is employer-friendly. While I have successfully set up print settings in chrome and firefox resulting in a 2-page format, safari and edge display it as 4 pages. An impo ...

JavaScript puzzle: Deciphering the differences between objects, arrays, and arrays containing objects

Having a rough coding day today. I can't seem to figure out why this code on fiddle isn't behaving as expected. var masterList = new Array(); var templates = new Array(); templates.push({"name":"name 1", "value":"1234"}); templates.push({"name": ...

What is the best way to upload images and generate permanent links for them using Express.js?

After successfully implementing the upload-part feature to my website, I encountered an issue. When I try to upload a file that is not a picture, the website displays an empty bracket []. My intention is to reject any non-picture uploads altogether. I am ...

Extracting data from a website using R

I'm currently attempting to extract information such as the names, cities, states, emails, etc of professionals from the website using rvest. However, I'm facing difficulties in identifying the CSS selectors with selector gadget and it appears t ...

The API request was resolved without a response, potentially causing delays in processing requests when using Multer and Next Connect to upload files

I have encountered an issue with my API even though it is running smoothly. The error message in the console states that the API resolved without sending a response, which could lead to stalled requests. I am using multer and next-connect in next.js for fi ...