【问题标题】:How to output TreeModel Js model as JSON如何将 TreeModel Js 模型输出为 JSON
【发布时间】:2020-03-19 21:58:51
【问题描述】:

所以我尝试使用 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
}

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

【问题讨论】:

  • 为什么不像 root.walk 那样创建对象/数组?
  • 认为嵌套的复杂性太深才能创建所需的树,这就是我首先依赖库的原因

标签: javascript treemodel


【解决方案1】:

试试JSON.stringify(root.model)

【讨论】:

  • 好的,我必须添加一些东西,我之前已经尝试过,但由于某种原因没有工作并输出:“null”,但现在尝试后它工作了,也许我修复了另一个地方的问题,但这仍然是只输出模型的正确方法,谢谢你提醒我回到开始。
  • 现在唯一的问题是类别模型的变化没有反映,例如:添加另一个对象键,输出仍然没有变化。
猜你喜欢
  • 2018-06-28
  • 1970-01-01
  • 1970-01-01
  • 2015-02-13
  • 1970-01-01
  • 2021-06-18
  • 2011-01-18
  • 1970-01-01
  • 2012-03-21
相关资源
最近更新 更多