javascripttreemodel

How to output TreeModel Js model as JSON


So I'm triyng to update some ids from a categories tree using TreeModelJS.

after editing I would like to dump the tree to a file in JSON format.

but when outputing other keys from TreeModel gets outputed as well.

How could I output edited tree as JSON (model only)?

I managed to replace other keys values with null and so far I got this:

const axios = require('axios')
const TreeModel = require('tree-model')
const fs = require('fs')

const url = 'https://my-api-uri-for-categories'
const dumpPath = `${process.cwd()}/data/test/categories.json`

const getCategories = async () => {
  try {
    const response = await axios.get(url)
    return response.data.categories
  } catch (error) {
    console.log('Error reading categories', error)
  }
}

const dumpJsonTofile = data => {
  try {
    console.log('Dumping to file')
    console.log(data)
    fs.writeFileSync(
      dumpPath,
      JSON.stringify(data, (k, v) => {
        if (k === 'parent' || k === 'config' || k === 'children') return null
        else return v
      }),
      'utf8'
    ) // write it back
  } catch (error) {
    console.log('Error dumping categories', error)
  }
}

const scraping = async category => {
  try {
    const response = await axios.get(category.url)
    const document = response.data
    const json = document.match(/{"searchTerm"(.*);/g)[0]
    const data = JSON.parse(json.replace(';', ''))
    return data
  } catch (error) {
    console.log(`Error while scraping category: ${category.name}`, error)
  }
}

async function run() {
  const categories = await getCategories()
  const categoriesTree = new TreeModel({
    childrenPropertyName: 'items',
  })
  const root = categoriesTree.parse({ id: 0, origin: {}, items: categories })
  root.walk(async node => {
    const category = node.model
    console.log(`scraping category: ${category.name}...`)
    if (!category.url) return console.log(`skipping (root?)...`)
    const data = await scraping(category)
    category.id = data.categoryId
  })
  dumpJsonTofile(root)
}

run()

but that still outputs a Node object like this:

{
   "config":null,
   "model":{},
   "children":null
}

I need to output all the tree showing only the model key value for each item


Solution

  • Try JSON.stringify(root.model).