【问题标题】:Convert string with dot notation to JSON将带点符号的字符串转换为 JSON
【发布时间】:2014-04-10 10:40:33
【问题描述】:

给定一个字符串作为点表示法,我将如何从该字符串创建一个对象(检查已经存在的属性):例如

var obj = {};
stringToObj('a.b', 'value1', obj);
stringToObj('a.b.c', 'value2', obj);

会产生

{
   "a": {
    "b": {
        "_x": "value1",
        "c": {
            "_x": "value2"
        }
    }
    }
 }

我查看了this questionthis one,但对于我正在做的事情似乎都不够。

有什么想法吗?

【问题讨论】:

  • 这里没有 JSON。
  • 或对象..土豆/potAto..
  • 更像苹果/橙子。 JSON 是一个字符串,它以与 JavaScript 兼容的符号表示对象。一个对象是……一个对象。

标签: javascript object


【解决方案1】:

对于那些正在寻找对象中没有 _x 的解决方案的人,请尝试此代码。对上述代码稍作修改(非常棒)

stringToObj = function(path,value,obj) {
  var parts = path.split("."), part;
  var last = parts.pop();
  while(part = parts.shift()) {
   if( typeof obj[part] != "object") obj[part] = {};
   obj = obj[part]; // update "pointer"
  }
 obj[last] = value;
}

如果您想更新现有对象的某些部分,上述代码将起作用:)

 var obj = {a:{b:3}};
 stringToObj("a.b",10,obj);
 console.log(obj); //result : {a:{b:10}}

【讨论】:

  • 这个解决方案正是我所需要的,您为我节省了数小时的工作时间。谢谢陌生人。
  • 解决问题的好方法
【解决方案2】:

您可以利用参考资料:

function stringToObj(path,value,obj) {
    var parts = path.split("."), part;
    while(part = parts.shift()) {
        if( typeof obj[part] != "object") obj[part] = {};
        obj = obj[part]; // update "pointer"
    }
    obj["_x"] = value;
}

【讨论】:

    【解决方案3】:

    为了扩展 @ilikeopensource 和 @Niet the Dark Absol 的答案,我需要添加对数组(同一路径的多个实例)的支持,并可以使用嵌套对象。我的情况更像是点符号和 json 字符串的混合体。

    function stringToObj(path, value, obj) {
        var objValue = value;
        try {
            objValue = JSON.parse(value);
        } catch (e) { } //eat the error, must not be json so carry on... Hack to do a valid JSON check
    
        var parts = path.split("."), part;
        var last = parts.pop();
        while (part = parts.shift()) {
            if (typeof obj[part] != "object")
                obj[part] = {};
            obj = obj[part];
        }
        if (obj.hasOwnProperty(last) && obj[last] && obj[last].constructor === Array) {
            obj[last].push(objValue);
        }
        else if (obj.hasOwnProperty(last) && obj[last]) {
            var objArray = [];
            objArray.push(obj[last])
            objArray.push(objValue);
            obj[last] = objArray;
        }
        else {
            obj[last] = objValue;
        }
    }
    

    感谢大家的帮助!

    【讨论】:

    • 你能给出你所支持的示例输入吗? IE。 “支持数组”当然还有预期的输出。
    【解决方案4】:

    这可能已经得到了很好的回答,但我想与那些仍在寻找不同方法的人分享我的解决方案。

    如果您想将字符串点表示法转换为字符串 JSON,这是我的方法。

    function dotToJson({ notation, inclusive = true, value = null }) {
      const fragments = notation.split(".").reverse();
    
      if (!inclusive) {
        fragments.pop();
      }
    
      console.log(fragments);
    
      return fragments.reduce((json, fragment) => {
        if (isNaN(fragment)) {
          return `{ "${fragment}": ${json} }`
        }
    
        let fill = "";
    
        if (Number(fragment) > 0) {
          for (let i = 0; i < fragment; i++) {
            fill += "null, "
          }
        }
    
        return `[${fill}${json}]`;
      }, JSON.stringify(value));
    };
    
    Attribute Meaning
    notation Dot notation string
    inclusive Include the root fragment
    value Default value for leaf

    你可以在这里看到结果,我使用 Quokka.js 测试过

    注意:除此之外,这可能有助于更新对象,因为您可以将扩展运算符与 JSON 的解析版本一起使用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-19
      • 2019-11-18
      • 1970-01-01
      • 2016-04-25
      相关资源
      最近更新 更多