json.js 1.2 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6 7
const fs = require('fs')
const path = require('path')
const stripJsonComments = require('strip-json-comments')

function parseJson (content, preprocess = false) {
  if (typeof content === 'string') {
    if (preprocess) {
fxy060608's avatar
fxy060608 已提交
8 9 10 11
      const preprocessor = require('@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader/preprocess')
      const {
        jsPreprocessOptions
      } = require('./platform')
fxy060608's avatar
fxy060608 已提交
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
      content = preprocessor.preprocess(content, jsPreprocessOptions.context, {
        type: jsPreprocessOptions.type
      })
    }
    content = JSON.parse(stripJsonComments(content))
  }

  content = JSON.stringify(content)
    .replace(/\u2028/g, '\\u2028')
    .replace(/\u2029/g, '\\u2029')

  return JSON.parse(content)
}

function getJson (jsonFileName, preprocess = false) {
  const jsonFilePath = path.resolve(process.env.UNI_INPUT_DIR, jsonFileName)
  if (!fs.existsSync(jsonFilePath)) {
    throw new Error(jsonFilePath + ' 不存在')
  }
  try {
    return parseJson(fs.readFileSync(jsonFilePath, 'utf8'), preprocess)
  } catch (e) {
    console.error(jsonFileName + ' 解析失败')
  }
}

module.exports = {
  getJson,
  parseJson
}