Extract certain attributes from a Json file and create a new Json dataset

My WordPress website has an API that exports posts as a Json file. I am working on a new website that will use this data, but I need to reformat the Json file with my custom property names and exclude some properties. Here is an example of the Json output from a post:

{
  "status": "ok",
  "post": {
    "id": 2335,
    "type": "post",
    "slug": "litoral-awards14-no-jornal-diario-porto-canal",
    "url": "https:\/\/litoralmagazine.com\/litoral-awards14-no-jornal-diario-porto-canal\/",
    ...
   }
}

I want to create a script that transforms this Json into a new format like below:

{
  "status": "ok",
  "slug": "litoral-com-teste-noticia-url",
  "title": "Titulo de teste",
  "type": "post",
  ...
   }
}

For instance: originalJson.status = newJson.status, originalJson.author.id = newJson.author, originalJson.thumbnail.url = newJson.images.thumbnail_image.

In the original Json, the 'content' property contains HTML code which I want to remove when creating the new Json. How can I achieve this?

I have searched for solutions but haven't found any. Is there a JavaScript script that can take the old Json input and output a new Json file with customized properties as described above?

Any help or suggestions would be greatly appreciated. Thank you!

Answer №1

When dealing with a valid HTML string, you have the option to utilize this specific function for text extraction:

function extractText(selector, html) {
  const elem = document.createElement('div');
  elem.innerHTML = html;

  return elem.querySelector(selector).innerText;
}

To implement this function, follow these steps:

const extractedText = extractText('p.some-selector', "<div id=\"some_id\">...");
// The extracted text will now be available for further use

It is important to note that if the selector does not locate any elements within the HTML, an error will occur. It is advisable to manage this scenario appropriately.

Answer №2

When tackling your initial inquiry without specifying the dynamically desired fields, you can enhance readability with this approach:

newJson = { 
    status: oldJson.status,
    author: oldJson.author
}

In response to your second question: To eliminate the div elements, consider these methods:

  • Utilize the replace function to substitute <div and ></div with an empty string
  • Iterate through the string to locate the first-next occurrence of index of <div and the subsequent index of >, then utilize substring to extract the string in between.

Exploring alternate avenues for fetching the html data before resorting to string manipulation is advisable from my standpoint.

Answer №3

give it a go:

const textString = { "status": "ok", "post": { "id": 2335, "categories": [ { "id": 299, "slug": "litoral-awards", "title": "Litoral Awards", "description": "", "parent": 0, "post_count": 91 }, ], }, "previous_url": "", "next_url": "" };

let statusValue = textString.status;
let postContent = textString.post;
let previousLink = textString.previous_url;
let nextLink = textString.next_url;
console.log('info:', textString.post.categories[0]);

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

Easily adding multiple field data with the same field name into a database can be achieved using Mongoose and Node.js (specifically Express

I am new to using nodejs and exploring the creation of a project focused on generating invoices. My goal is to store product information in mongodb utilizing mongoose and express, but I'm unsure of how to proceed. Below is a snippet of my HTML code.. ...

What is the best way for Selenium to efficiently handle multiple calls to isElementDisplayed()?

Selenium offers a convenient method for fetching numerous elements from the DOM efficiently in one quick round-trip: buttons = driver.find_elements_by_css_selector('button') The retrieved buttons can include dozens or hundreds of elements with ...

Safari 15.6.1 does not support background video playback in Next.js

Currently using Safari version 15.6.1 for a small website project, I have encountered an issue where the video appears frozen with an arrow in the middle. Oddly enough, this problem only occurs on Safari as both Chrome and Firefox display the code correctl ...

Error: Incompatibility - The variable is not functioning properly in node.js or express.js

Upon encountering the error message "TypeError: undefined is not a function," I called a callback with parameters null, array_reply, and threadResults. It appears that this section of code is problematic, but I am uncertain why. Your assistance in resol ...

Tips for displaying boolean fields in Web API responses

Currently in the process of designing a REST Web API, grappling with some uncertainty on how to structure certain parts of the response. An example showcasing the intended output would likely provide the best clarity, which is presented below: Example 1: ...

Modifying JSON Values within a File Using Jansson

I am encountering an issue with changing values in a JSON file and saving the modifications. Despite successfully loading the file, the changes I make are not being saved at all. How can I resolve this problem? Starting from /home/pi/desktop/test.json { ...

What might be causing the issue in the build process of my next.js project?

**Why is my Node.js YAML file causing an error?** name: Node.js CI on: push: branches: [ "main" ] pull_request: branches: [ "main" ] jobs: build: runs-on: ubuntu-latest strategy: matrix: node-ver ...

Utilizing a range input (slider) to extract data of importance

When dynamically adding a slider to a page using a specific string, like the one shown below: "<input type=\"range\" name=\"aName\" min=\"1\" max=\"9\"/>"; After appending it to the page with pure JavaScript, ...

Exploring Unanchored Substring Queries in Loopback API

Searching for a solution to implement a basic substring query using the loopback API for a typeahead field. Despite my efforts, I have not been able to find a clear answer. I simply want to input a substring and retrieve all brands that contain that subst ...

Retrieve JavaScript functions as JSON or text in AngularJS and execute them

Currently, I am working on developing an AngularJS application and have come across a particular challenge that needs to be addressed: After making a web service call, I receive JavaScript code that looks like this: { "script":"function foo(a, b) { c = ...

What could be the reason my Minecraft location_check predicate isn't executing?

I diligently followed numerous tutorials and successfully implemented the "player is_sprinting:true" predicate in my newly created datapack. This proves that my datapack is functioning properly. Despite my thorough research, I could not find any examples ...

Unable to display arrow D3 graph on SVG

I've been puzzling over this issue for quite some time... I have an SVG that is displaying nodes and links for a directed graph. However, the lines are not displaying arrows. Here is the troublesome code snippet for the arrow. While the nodes and lin ...

What is the best way to test a component that does not properly handle a rejected promise using `wait` in the react-testing-library?

Looking to simulate a failed AJAX request scenario when placing an order on an online shopping store. Additionally, users can choose to subscribe only if the order placement is successful. Currently facing issues with handling Promise rejection in the tes ...

Adjust the object size to match the Viewport dimensions

I've been developing a VR world where the camera can be turned and tilted in the center but not moved around freely. Within this virtual reality environment, you have the ability to attach a video to the background. Users can either play it by clicki ...

Tips for effectively closing div elements

How can I modify this accordion to close when a user clicks on another link, and also change the image of the open "p" tag? Currently, clicking on a link toggles the content and changes the image. However, what I am struggling with is closing the previousl ...

Exploring and extracting nested JSON data within Snowflake

I'm dealing with a table containing file data structured like the example below in each row. I need to flatten this file for parsing, but when using lateral flatten, I'm encountering issues with NULL values in nested files (history, dealer, vehic ...

Unable to transfer Vue.js components in and out of the project

I have a directory structured like this. VueTree components Classic.vue Modern.vue index.js The Classic and Modern components consist of a template, export default {}, and a style. I am importing both of them in index.js as: import Classic ...

Exploring the Possibilities with NodeJS and Socket.IO

I've encountered an interesting issue with my use of NodeJS and Socket.io. The server receives data through ZeroMQ, which is working perfectly fine. However, when there are a large number of connected clients (over 100), it appears that there is a de ...

Controlling Development, Production, and Staging App Settings in Azure Functions

I am diving into Azure functions and exploring how to handle app settings based on the environment. In dotnet core, you would typically use files like appsettings.json, appsettings.development.json, etc. to manage configurations for different environments ...

Decoding JSON string List<string> data in a JsonResult MVC

Having trouble deserializing a JSON string to MyModel and receiving an "Error" from my AJAX call: $.ajax({ type: 'POST', traditional: true, url: '/Employee/Extract', ...