首页 > 解决方案 > 如何从 js 文件代码字符串(由 fs.readFileSync 获得)中获取部分 json?

问题描述

var a = {
    properties:{
        title:{
            type:"String",
            value:"sss"
        },
        content:{
            type:"String",
            value:"555"
        }
    },
    data:{
        abc:123,
        ddd:444,
        fff:"dd"
    },
    methods: {
        abc () {

        },
        cde () {

        }
    }
}

上面的代码是来自 js 文件的文本字符串(由 fs.readFileSync 获取)。我需要通过正则表达式获取“属性”字符串的一部分并将其解析为 json 对象。

标签: javascriptnode.jsregexobject

解决方案


您可以使用object Destructuring

const {properties} = a;

var a = {
  properties: {
    title: {
      type: "String",
      value: "sss"
    },
    content: {
      type: "String",
      value: "555"
    }
  },
  data: {
    abc: 123,
    ddd: 444,
    fff: "dd"
  },
  methods: {
    abc() {

    },
    cde() {

    }
  }
}

const {properties} = a;

console.log(properties);

或使用dot运营商访问

a.properties

或者

a["properties"]


推荐阅读