Reputation: 3934
I have a properties files which contain the following text
var propertiesString = `
alerts.attachment-preview-unavailable=Preview unavailable for this file.
alerts.operation-failed-unknown=Oops, operation failed for unknown reason.
comments.actions.approve.all.success=All comments in this discussion are approved.
comments.actions.approve.one.success=Comment approved.
comments.members.phrases.someone-plus-others={{someone}} + {{countOthers}} others
`;
Now I am trying to convert these properties to JSON object which is the following
{
"alerts": {
"attachment-preview-unavailable": "Preview unavailable for this file.",
"operation-failed-unknown": "Oops, operation failed for unknown reason."
},
"comments": {
"actions": {
"approve": {
"all": {
"success": "All comments in this discussion are approved."
},
"one": {
"success": "Comment approved."
}
}
},
"members": {
"phrases": {
"someone-plus-others": "{{someone}} + {{countOthers}} others"
}
}
}
}
var propertiesString = `alerts.attachment-preview-unavailable=Preview unavailable for this file.
alerts.operation-failed-unknown=Oops, operation failed for unknown reason.
colors.green=Green
colors.red=Red
comments.actions.approve.all.success=All comments in this discussion are approved.
comments.actions.approve.one.success=Comment approved.
comments.actions.unpin.success=Comment has been unpinned.
comments.actions.unsee.success=You marked this comment as unseen.
comments.form.at-mention-restriction-on-pending-ideas=You may only @mention other moderators and the idea submitter while the idea is in pending approval.
comments.form.attachment.upload.error.unknown=Oops, unknown error happened when uploading the comment's attachment.
members.phrases.someone-plus-others={{someone}} + {{countOthers}} others
time-ago.on.day-month=on {{day}}{{ordinalSuffix}} {{month}}
time-ago.on.day-month-year=on {{day}}{{ordinalSuffix}} {{month}} {{year}}
time-ago.week.0=Sunday
time-ago.week.1=Monday
time-ago.week.2=Tuesday
time-ago.week.3=Wednesday
time-ago.week.4=Thursday
time-ago.week.5=Friday
time-ago.week.6=Saturday`;
function propertiesToJSON(str) {
str
// Concat lines that end with '\'.
.replace(/\\\n/, "")
// Split by line breaks.
.split("\n")
// Remove commented lines:
.filter((line) => /(\#|\!)/.test(line.replace(/\s/g, "").slice(0, 1)) ? false : line)
// Create the JSON:
.reduce((obj, line) => {
const colonifiedLine = line.replace(/(\=)/, ":");
const key = colonifiedLine
.substring(0, colonifiedLine.indexOf(":"))
.trim();
const value = colonifiedLine
.substring(colonifiedLine.indexOf(":") + 1)
.trim();
obj[key] = value;
return obj;
}, {});
}
console.log(propertiesToJSON(propertiesString));
Upvotes: 0
Views: 1762
Reputation: 6778
Lodash library has a function set
you are looking for
var propertiesString = `
alerts.attachment-preview-unavailable=Preview unavailable for this file.
alerts.operation-failed-unknown=Oops, operation failed for unknown reason.
comments.actions.approve.all.success=All comments in this discussion are approved.
comments.actions.approve.one.success=Comment approved.
comments.members.phrases.someone-plus-others={{someone}} + {{countOthers}} others
`;
var result = propertiesString
.split("\n") //divides lines
.filter(Boolean) //removes empty lines
.reduce((acc, line) => {
_.set(acc, ...line.split("="));
return acc;
}, {})
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
As requested here is code with implementation of lodash method set
with pure javascript without any external libraries
const set = (obj, path, value) => {
if (Object(obj) !== obj) return obj; // When obj is not an object
// If not yet an array, get the keys from the string-path
if (!Array.isArray(path)) path = path.toString().match(/[^.[\]]+/g) || [];
path.slice(0,-1).reduce((a, c, i) => // Iterate all of them except the last one
Object(a[c]) === a[c] // Does the key exist and is its value an object?
// Yes: then follow that path
? a[c]
// No: create the key. Is the next key a potential array-index?
: a[c] = Math.abs(path[i+1])>>0 === +path[i+1]
? [] // Yes: assign a new array object
: {}, // No: assign a new plain object
obj)[path.pop()] = value; // Finally assign the value to the last key
return obj; // Return the top-level object to allow chaining
};
var propertiesString = `
alerts.attachment-preview-unavailable=Preview unavailable for this file.
alerts.operation-failed-unknown=Oops, operation failed for unknown reason.
comments.actions.approve.all.success=All comments in this discussion are approved.
comments.actions.approve.one.success=Comment approved.
comments.members.phrases.someone-plus-others={{someone}} + {{countOthers}} others
`;
var result = propertiesString
.split("\n") //divides lines
.filter(Boolean) //removes empty lines
.reduce((acc, line) => {
set(acc, ...line.split("="));
return acc;
}, {})
console.log(result)
Upvotes: 5