GULP Создать файл JSON из другого файла JSON - PullRequest
0 голосов
/ 27 мая 2019

Я пытаюсь создать локальный файл lang, который будет отформатирован как json.У меня есть следующая навигация в формате JSON ниже.И мне нужно создать новый файл JSON, используя GULP для создания файла lang (см. Ниже)

  "lists": [
    {
      "title": "Application Intel",
      "items": [
        {
          "title": "Analytics Dashboard",
          "href": "intel_analytics_dashboard.html"
        },
        {
          "title": "Marketing Dashboard",
          "href": "intel_marketing_dashboard.html"
        },
        {
          "title": "CEO Dashboard",
          "href": "intel_ceo_dashboard.html"
        },
        {
          "title": "Introduction",
          "href": "intel_introduction.html"
        },
        {
          "title": "Build Notes",
          "href": "intel_build_notes.html",
          "text": "Build Notes",
          "span": {
            "class": "",
            "text": "v{{version}}"
          }
        }
      ]
    }

Мне нужно создать файл, который выглядит следующим образом json:

  "nav": {
    "application_intel": "Application Intel",
    "intel_analytics_dashboard": "Analytics Dashboard",
    "intel_marketing_dashboard": "Marketing Dashboard",
    "intel_ceo_dashboard": "CEO Dashboard",
    "intel_introduction": "Introduction",
    "intel_build_notes": "Build Notes",
  }

Какой лучший способ пойти по этому поводу?

1 Ответ

1 голос
/ 29 мая 2019

Вот решение. Допустим, у вас есть файл nav.json внутри src, и вы хотите изменить его форму и поместить его в каталог dest. Вы можете достичь этого из gulpfile.js

const { src, dest } = require("gulp");
const through = require("through2");

// gulp task
function json() {
  return src("src/nav.json")
    .pipe(
      through.obj((file, enc, cb) => {
        // get content of json file
        const rawJSON = file.contents.toString();

        // parse raw json into javscript object
        const parsed = JSON.parse(rawJSON);

        // transform json into desired shape
        const transformed = transformJson(parsed);

        // make string from javascript obj
        const stringified = JSON.stringify(transformed, null, 2);

        // make bufer from string and attach it as current file content
        file.contents = Buffer.from(stringified);

        // pass transformed file into next gulp pipe
        cb(null, file);
      })
    )
    .pipe(dest("dest"));
}

// transformation
function transformJson(input) {
  const result = { nav: {} };

  // read json field by field
  Object.keys(input).forEach(topLevelKey => {
    // current object
    const topLevelItem = input[topLevelKey];

    // in your design topLevelItems are arrays
    topLevelItem.forEach(menuItem => {
      if (menuItem.title) {
        // make url either from item href or title
        const itemUrl = makeUrl(menuItem.href || menuItem.title);
        result.nav[itemUrl] = menuItem.title;
      }

      // prcoess children
      if (menuItem.items) {
        menuItem.items
          .filter(child => !!child.title) // process only child items with title
          .forEach(child => {
            const childUrl = makeUrl(child.href || child.title);
            result.nav[childUrl] = child.title;
          });
      }
    });
  });

  return result;
}

// helper func
function makeUrl(href) {
  return href
    .toLowerCase()
    .replace(/\.html$/, "")
    .replace(/\s/g, "_");
}

// export for use in command line
exports.json = json;

Функция преобразования json - это бит forEachy , и если у вас есть глубоко вложенная структура навигации, возможно, вам следует изменить ее на нечто рекурсивное

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...