不使用JSON解析字符串对象

时间:2017-11-14 09:43:29

标签: javascript parsing

我需要从html元素属性解析一个对象(比如angular就是这样),而不使用JSON.parse或其他东西

例如,我有DIV这样的

<div some-attribute="{key1: 1 > 0, key2: true || false}"></div>

在解析之后,我只需要在此对象中拥有所有内容的字符串表示:

{'key1': '1 > 0', 'key2': 'true || false'}

有没有能力以这种方式解析它而不发明新的解析器?

2 个答案:

答案 0 :(得分:2)

你想最终获得[Object]吗?您可以在[String]值中搜索,:,然后将其拆分为:

&#13;
&#13;
//retrieve this from attribute with DOM methods
var a = "{key1: 1 > 0, key2: true || false}";

console.log(parse(a));

function parse(data) {
  if (data[0] !== '{' || data[data.length - 1] !== '}') return null; //remove it if useless
  var props = data.slice(1, data.length - 1).split(/\s*,\s*/);
  var newObj = {};
  props.forEach((a) => {
    var pair = a.split(/\s*:\s*/);
    newObj[pair[0]] = pair[1];
  });
  return newObj;
}
&#13;
&#13;
&#13;

RegExp删除了,:

之间的空格

答案 1 :(得分:0)

感谢所有人,我意识到我应该为此创建一个解析器。这是第一个版本(在Coffee上,而不是纯JS)

class Parser
    self = @

    constructor: ->

    @quotes: '\'"`'

    @object: (dataStr) ->
        dataStr = $dp.fn.trim dataStr
        if dataStr[0] isnt '{' or dataStr.slice(-1) isnt '}'
            return null
        dataStr = dataStr.slice 1, dataStr.length - 1

        o = {}
        pair =
            key: ''
            value: ''
        addPair = ->
            o[$dp.fn.trim(pair.key)] = $dp.fn.trim pair.value
            pair.key = pair.value = ''
        quoteOpened = null
        underCursor = 'key'

        for ch, i in dataStr
            skip = false

            if ch in self.quotes
                unless quoteOpened
                    quoteOpened = ch
                    skip = true
                else if quoteOpened and ch is quoteOpened
                    quoteOpened = null
                    skip = true

            unless quoteOpened
                switch
                    when ch is ':'
                        underCursor = 'border'
                    when underCursor is 'border' and not /\s/.test ch
                        underCursor = 'value'
                    when ch is ','
                        underCursor = 'key'
                        addPair()
                        skip = true

            pair[underCursor] += ch if underCursor isnt 'border' and not skip

        addPair() if pair.key or pair.value
        o