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?
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.
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.
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.
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.
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
NOTE: Additionally to this, thiss may help to update objects because you can use spread operator with the parsed version of the JSON
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}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With