Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string with dot notation to JSON

Given a string as dot notation, how would I create an object from that string (checking for already existing properties): eg

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

would produce

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

I've looked at this question and this one but neither seems to be sufficient for what Im doing.

Any thoughts?

like image 584
stephen mc Avatar asked Apr 10 '14 10:04

stephen mc


People also ask

Can JSON use dot notation?

Dot notation is designed for easy, general use and common use cases. Queries of JSON data that use dot-notation syntax return JSON values whenever possible. The return value for a dot-notation query is always a string (data type VARCHAR2(4000) ) representing JSON data.

How do I convert a string to JSON?

String data can be easily converted to JSON using the stringify() function, and also it can be done using eval() , which accepts the JavaScript expression that you will learn about in this guide.

Can JSON field names have dots?

Unlike MongoDB, which does not allow dots, ( . ), in JSON or BSON field names, IBM® Informix® conforms to the JSON standard and allows dots. For example: {"user. fn" : "Jake"}. However, you cannot run a query or an operation directly on a field that has a dot in its name.

Can we convert string to JSON in Python?

you can turn it into JSON in Python using the json. loads() function. The json. loads() function accepts as input a valid string and converts it to a Python dictionary.


2 Answers

This may be well answered already, but I would like to share my resolution for those who still looking for a different approach.

If you would like to convert string dot notation to a string JSON, here's my approach.

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

You can see the results here, I tested it using Quokka.js

Final screenshot

NOTE: Additionally to this, thiss may help to update objects because you can use spread operator with the parsed version of the JSON

like image 131
kingbeencent Avatar answered Sep 21 '22 15:09

kingbeencent


For those of you who are looking for solution without the _x in the object try this code. A slight modification of the above code (which is brilliant)

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;
}

As bonus the above code will work if you want to update parts of an existing object :)

 var obj = {a:{b:3}};
 stringToObj("a.b",10,obj);
 console.log(obj); //result : {a:{b:10}}
like image 26
ilikeopensource Avatar answered Sep 17 '22 15:09

ilikeopensource