Home > Net >  How to delete the element which matches filter within the list in object of JSON
How to delete the element which matches filter within the list in object of JSON

Time:12-04

Sorry for my French and stupid question, but i need to DELETE some elements in JSON file while I don't now anything in JSON and JS

There is the structure: `

{ "questions": [
    {
        "id": 1,
        "quizId": 1,
        "question": "Какому автомобилю разрешается остановка в зоне действия этих знаков?",
        "correctAnswer": 4,
        "image": "1.jpg",
        "answers": [
            "Красному.",
            "Обоим автомобилям.",
            "Ни одному.",
            "Ни одному.",
            "Желтому, обозначенному опознавательным знаком \"Инвалид\".",
            "-"
        ]
    },
    {
        "id": 2,
        "quizId": 1,
        "question": "По каким направлениям из числа обозначенных стрелками разрешается движение?",
        "correctAnswer": 4,
        "image": "2.jpg",
        "answers": [
            "Только по направлению А.",
            "Только по направлению Б.",
            "Только по направлению В.",
            "-",
            "-",
            "-."
        ]
    } 
]
}

And I need to find the elements within answers array which equals to "-" and delete it.

So output should be:

{ "questions": [
    {
        "id": 1,
        "quizId": 1,
        "question": "Какому автомобилю разрешается остановка в зоне действия этих знаков?",
        "correctAnswer": 4,
        "image": "1.jpg",
        "answers": [
            "Красному.",
            "Обоим автомобилям.",
            "Ни одному.",
            "Ни одному.",
            "Желтому, обозначенному опознавательным знаком \"Инвалид\".",
        ]
    },
    {
        "id": 2,
        "quizId": 1,
        "question": "По каким направлениям из числа обозначенных стрелками разрешается движение?",
        "correctAnswer": 4,
        "image": "2.jpg",
        "answers": [
            "Только по направлению А.",
            "Только по направлению Б.",
            "Только по направлению В."
        ]
    } 
]
}

I tried to solve the problem, but unsuccessfully. Thanks for your answers!

CodePudding user response:

To accomplish this task, you could use some server-side scripting, I recommend NodeJS as it is directly related to JS.

You can see the documentation here: https://nodejs.dev/en/

Within the NodeJS project, you will have to use the File System module https://nodejs.org/api/fs.html

Having the above configured, the code would be 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 above code can be described as follows:

  • The FileSystem module is imported
  • A constant is created which contains the path where your .json file is located
  • We create a variable “json_file_content” which will contain the content of your .json file

To get this content, do the following:

  • Get the content of your file using readFileSync
  • This content is converted to string type using toString
  • Subsequently, it is converted to JSON using JSON.parse

Having the json in a variable, simple JS code can now be applied, Inside that code what is happening is this:

  • All questions contained in the object are iterated
  • For each question, their answers are accessed
  • The answers are filtered, eliminating those that are equal to "-" and "-."

Finally:

  • The filtered json is converted to a string
  • The new string (JSON) is written into your file using writeFileSync
  • Related