Tips for removing the element that meets the criteria from a JSON object list

Apologies for the lack of knowledge in French and for asking what may seem like a silly question, but I need assistance with removing certain elements from a JSON file despite being unfamiliar with JSON and JS.

The structure is as follows: `

{ "questions": [
    {
        "id": 1,
        "quizId": 1,
        "question": "Which vehicle is allowed to stop within the area covered by these signs?",
        "correctAnswer": 4,
        "image": "1.jpg",
        "answers": [
            "To the red one.",
            "To both vehicles.",
            "To neither.",
            "To neither.",
            "To the yellow one marked with the identifier sign \"Disabled\".",
            "-"
        ]
    },
    {
        "id": 2,
        "quizId": 1,
        "question": "In which directions indicated by the arrows is movement permitted?",
        "correctAnswer": 4,
        "image": "2.jpg",
        "answers": [
            "Only in direction A.",
            "Only in direction B.",
            "Only in direction C.",
            "-",
            "-",
            "-"
        ]
    } 
]
}

I am looking to identify elements within the answers array that equal "-" and remove them.

Therefore, the desired output should be:

{ "questions": [
    {
        "id": 1,
        "quizId": 1,
        "question": "Which vehicle is allowed to stop within the area covered by these signs?",
        "correctAnswer": 4,
        "image": "1.jpg",
        "answers": [
            "To the red one.",
            "To both vehicles.",
            "To neither.",
            "To neither.",
            "To the yellow one marked with the identifier sign \"Disabled\"."
        ]
    },
    {
        "id": 2,
        "quizId": 1,
        "question": "In which directions indicated by the arrows is movement permitted?",
        "correctAnswer": 4,
        "image": "2.jpg",
        "answers": [
            "Only in direction A.",
            "Only in direction B.",
            "Only in direction C."
        ]
    } 
]
}

I attempted to solve the problem on my own without success. Thank you for any guidance provided!

Answer №1

If you're looking to achieve this task, consider incorporating server-side scripting with NodeJS, a seamless extension of JavaScript.

Refer to the official documentation for NodeJS here:

Within your NodeJS project, utilize the File System module found at: https://nodejs.org/api/fs.html

After setting up as mentioned above, the code snippet can be implemented as follows:

import fs from "fs"
const file_path = “YOUR_JSON_FILE_PATH”

let json_file_content = JSON.parse(fs.readFileSync(file_path).toString());

  for (let i in json_file_content.questions) {
    json_file_content.questions[i].answers = 
    json_file_content.questions[i].answers.
    filter(answer => (answer != "-" && answer != "-."))
  }
 
fs.writeFileSync(file_path, JSON.stringify(json_file_content));

The breakdown of the code is summarized below:

  • Importing the FileSystem module
  • Defining a constant holding the path to your .json file
  • Creating a variable "json_file_content" to store the content of your .json file

Retrieve the content by following these steps:

  • Read the file content using readFileSync
  • Convert the content to string type using toString
  • Subsequently, parse it into JSON format using JSON.parse

With the JSON stored in a variable, regular JS code can be applied, whereby:

  • All questions within the object are iterated through
  • For each question, their respective answers are accessed
  • The answers are filtered, removing those matching "-" and "-."

To conclude:

  • The filtered JSON data is converted back to a string
  • This updated string (as JSON) is written back into your file utilizing writeFileSync

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

implementing a delay after hovering over a CSS hover effect before activating it

I'm trying to achieve a specific effect using JavaScript or jQuery, but I'm struggling to figure it out. I have created a simple CSS box with a hover effect that changes the color. What I want is for the hover effect to persist for a set amount o ...

What could be causing webpack to struggle in locating the loader?

Check out my package.json: { "name": "redux-todo", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "start": "webpack-dev-server" }, "devDependencies": { "babel": "^6.5.2", "babel-loader": "^6.2.5", "bab ...

Updating a string in JavaScript by dynamically adding values from a JSON object

In my current function, I am making a request to fetch data and storing it as an object (OBJ). Afterwards, I make another request to get a new URL that requires me to update the URL with values from the stored data. The information saved in the object is ...

Encountering a problem with the Ionic Modal Slider: unable to locate the matching element associated with delegate-handle= when using $

I am encountering a problem with my Ionic application that features multiple Angular controllers. Specifically, I have a LoginCtrl and RegisterCtrl controller set up. The issue arises when I try to trigger a modal with a slider from the RegisterCtrl by usi ...

What is the best way to inject a service instance into the implementation of an abstract method?

In my Angular application, I have a service that extends an abstract class and implements an abstract method. @Injectable({ providedIn: 'root', }) export class ClassB extends ClassA { constructor( private service : ExampleService) { s ...

combine several arrays next to each other based on a specified key

I have a collection of three sets, each containing three elements: Set1 = [[apple, 2, 4], [banana, 5, 5], [cherry, 4, 1]] Set2 = [[banana, 1, 7], [cherry, 3, 8], [date, 5, 4]] Set3 = [[apple, 5, 2], [banana, 0, 9], ...

Endless cycle of React hooks

I am struggling to understand why I keep encountering an infinite loop in my useClick function. I can see that I am updating the state value inside the useEffect using setVal, but according to the second parameter, useEffect should only run on onClick as ...

Navigating JSON responses and requests

Although I'm still relatively new to the programming language Go, I have managed to understand most of it quite well. However, I'm struggling with how JSON should be handled within the language. Let's say I have an access token on the front ...

Logging in Python: A Guide to JSON Formatting

Our Python Django application requires logging using the code snippet below in order to allow ELK to index the log record as JSON logger.info(json.dumps({'level':'INFO','data':'some random data'}) We currently have ...

React Component is not functioning with the timer running

I am currently developing a basic timer app using React. Here is the code snippet I have so far: import React from "react" const timer = (props) => { let time = 25; let processStatus = props.timerProcessStatus; // set to true if(processSta ...

Increasing the date field value in Mongoose, ExpressJS, and AngularJS with additional days

I encountered an issue while attempting to extend the number of days for an existing Date field in mongoose. Despite no errors being displayed in the browser or console, something seems to be amiss. Can anyone identify the problem in this code snippet? ...

Retrieve files from Amazon S3 using JavaScript

I'm currently working with a javascript file that's intended to download a text file from one of my S3 buckets. However, after running this file using "node file.js", nothing happens and there's no output. Is there something I'm missing ...

What is the best approach to integrating AJAX calls with promises in the Angular framework?

I'm facing an issue while using Angular promises with the $q service in my controller. Here's the code snippet: var myController = function ($scope, myService) { $scope.doSomething = function (c, $event) { $event.preventDefault(); ...

What is the most efficient method for designing this jQuery code to be reusable?

I am currently using dynamic Bootstrap popovers that are populated with content from my database. In PHP, it generates unique classes for each popover. My question is, when using jQuery, do I need to trigger the popovers individually? This is how I am cur ...

Using both withNextIntl and withPlaiceholder simultaneously in a NextJS project causes compatibility issues

I recently upgraded to NextJS 14 and encountered an issue when deploying my project on Vercel. The next.config.mjs file in which I wrapped my nextConfig in two plugins seemed to prevent the build from completing successfully. As a workaround, I decided t ...

Strange JSON format detected when consuming the Python Hug REST API in a .NET environment

When using a Hug REST endpoint to consume JSON in .net, there are issues with embedded characters that I am facing. See the example below for a complete failure. Any assistance would be greatly appreciated. Python @hug.post('/test') def test(re ...

Accessing the statusText of a 403 response in Axios (React, Express, Node.js)

Within my component, there is a register function that makes an API call. The API checks if the email already exists and provides an appropriate status and statusText based on the result. Below is the API call handler in my Express app: router.post(' ...

The file functions/lib/functions/src/index.ts is missing, preventing the deployment of Cloud Functions

Whenever I attempt to deploy my Firebase cloud functions, I encounter the following error. Expected outcome: Successful deployment of functions. Error: Error: An issue occurred while reading functions/package.json: functions/lib/index.js is missing and ...

What advantages come from destructuring in conjunction with require statements?

When utilizing require, is there a performance advantage or disadvantage to importing the entire module versus only importing selected functions? It's my understanding that when using require to import modules (as opposed to using import), compilers ...

A method designed to accept an acronym as an argument and output the corresponding full name text

Having trouble with my current task - I've got an HTML file and external JS file, and I need a function that takes an element from the 'cities' array as input and returns a string to be used in populating a table. I've set up a functio ...