如何将 TreeModel Js 模型输出为 JSON

How to output TreeModel Js model as JSON

所以我尝试使用 TreeModelJS 从类别树中更新一些 ID。

编辑后我想将树转储到 JSON 格式的文件中。

但是当从 TreeModel 输出其他键时也会输出。

如何将编辑后的树输出为 JSON(仅限模型)?

我设法用 null 替换了其他键值,到目前为止我得到了这个:

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()

但这仍然输出一个像这样的 Node 对象:

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

我需要输出所有只显示每个项目的模型键值的树

尝试JSON.stringify(root.model)