将字符串转换为格式不正确的JS对象

时间:2017-05-08 17:48:27

标签: javascript regex

我的字符串格式不正确,使用JavaScript,假设数据为:

{engine{type{condition},age},wheels,model{name},color}

我想将其转换为可用的(JS)对象。我可以使用正则表达式解析碎片,但我想知道是否有非正则表达式方法。如果你必须在正则表达式中这样做,最简单的方法是什么?

转换后的对象应该更像是:

{
 engine: {
  type: {
   condition: null
  },
  age: null
 },
 wheels: null,
 model: {
  name: null
 },
 color: null
}

我也可以从一系列嵌套数组中使用它。

1 个答案:

答案 0 :(得分:1)

嗯,假设那是" char {"应该是" char:{"和" char,"或"焦炭}"应该是" char = null,"或" char = null}",这是一个非常简单的查找和替换。否则,您可能必须使用递归解析函数将其拆分并将其重新组合在一起。



public class Gps {
    private int x;
    private int y;
    private int z;

    public int getX() {
        return this.x; 
    }

    public int getY() {
        return this.y; 
    }

    public int getZ() {
        return this.z; 
    }

    public void setX(int x) {
        this.x = x;
    }

    public void setY(int y) {
        this.y = y;
    }

    public void setZ(int z) {
        this.z = z;
    }
}


class City {
    Gps where;

    City(int x, int y, int z) {
       this.where = new Gps();
       where.setX(x);
       where.setY(y);
       where.setZ(z);
    }
}




相关问题