【问题标题】:I want to parse a .js config file in Groovy我想在 Groovy 中解析一个 .js 配置文件
【发布时间】:2021-11-03 15:05:52
【问题描述】:

我正在从 config.js 文件中读取此配置并尝试解析。我试过 JsonSlurper 没有运气。谁能让我知道在 groovy 中解析这个字符串的可行解决方案

exports.config = {
  tests: './test/lib/test*.js',
  output: './output',
  helpers: {
    WebDriver: {
      url: 'https://google.com/',
      browser: 'chrome',
      host: 'testhost.com',
      port: 80,
    },
  },
  plugins: {
    wdio: {
      enabled: false,
      services: [ 'selenium-standalone' ],
    },
  },
  include: {
    I: './steps_file.js',
  },
  mocha: {},
  name: 'testProject',
  modules: './main/lib/',
  pageobjects: './main/pageObjects/',
  pages: './main/pages/',
  testData: './test/resources/testData/',
};

【问题讨论】:

    标签: json parsing groovy codeceptjs


    【解决方案1】:

    除了开头的赋值和结尾的分号(和反引号?)之外,它似乎可以被视为大部分不符合要求的 json

    如果这些被剥离,剥离左大括号之前和从字符串末尾向后到右大括号的任何内容,那么您可能会在 jsonslurper 中使用 LAX 解析器,它允许不带引号的键和单引号。

    【讨论】:

    • 您好斯蒂芬,感谢您的回答。我尝试了以下方法并收到错误:import groovy.json.JsonParserType;导入 groovy.json.JsonSlurper; def obj = { 测试:'./test/lib/test*.js',输出:'./output' } def slurper = new JsonSlurper().setType(JsonParserType.LAX) def config = slurper.parse(obj) ; println(config) Script1.groovy: 5: unexpected token: ./test/lib/test*.js @ line 5, column 21.
    • @ManojRajan 请将代码添加到问题中
    【解决方案2】:

    Stephen 和@cfrick,我使用以下方法来实现我的要求:

    1. 使用 slurper 和 LAX 解析器来解析内容
    2. 读取配置文件并删除“exports.config =”。
    3. 导入LAX解析器并解析内容 新的 JsonSlurper().setType(RELAX).parseText()
    4. 然后使用 Map 使其成为 Hashmap 并使用 put 函数更新 key Map mappedData=(HashMap)slurpedData; mappedData.put("value" , value);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-11
      • 1970-01-01
      • 1970-01-01
      • 2011-03-22
      • 1970-01-01
      • 2017-06-03
      • 2014-09-15
      • 2014-09-04
      相关资源
      最近更新 更多