Home > Software design >  Convert a list of words and save in json file
Convert a list of words and save in json file

Time:11-25

I would like a list of words that I save in a json file by a request from an api. The words are without quotation marks and commas, for example:

name1 name2 name3

I want to save them in the following format in the json file

[
    "name1", 
    "name2",
    "name3"
 ]

the existing files can be overwritten. However, no duplicate words should be saved

With my code, it doesn't really save what I want

"name1" "name2" "name3"

this is my code


const data = JSON.parse(jsonObjekt);

data.forEach((follower, i) => {
  const element = data.data[i].to_name;
  var nameArr = JSON.stringify(element, null, 2).split(' ');
  fs.writeFileSync('names.json', JSON.stringify(element, null, 2).split(" ") ',', { 
  encoding: 'utf8', flag: 'a ' })

})

This is the jsonObjekt i get

{
  "total": 94,
  "data": [
  {
    "login": "username",
    "name": "name1"
  },
  {
    "login": "username",
    "name": "name2"
  },
  {
    "login": "username",
    "name": "name3"
  },
...
}

CodePudding user response:

Something like this?

const fs = require('fs')

const jsonObjekt = {
    "total": 94,
    "data": [
    {
      "login": "username",
      "name": "name1"
    },
    {
      "login": "username",
      "name": "name2"
    },
    {
      "login": "username",
      "name": "name3"
    }]}
let data = [];

jsonObjekt.data.forEach((follower, i) => {
    data.push(follower.name)
  })

fs.writeFileSync('names.json', JSON.stringify(data))
  • Related