Home > Enterprise >  convert properties to javascript object ( bad character result)
convert properties to javascript object ( bad character result)

Time:10-22

I have some problems with characters (ä, å, ö) usually I convert them to

å=\u00e5
ä=\u00e4
ö=\u00f6

I cannot get rid of these right now because I am using an old technology Apache Wicket. my Language.proprites file looks like this

calendar-event-group-configuration=Konfigurationsgrupp f\u00f6r 
evenemang

When I am reading .properties files I get in the console ( using a npm package called ('properties-reader')) :

Konfigurationsgrupp f\\u00f6r evenemang

I expect getting:

Konfigurationsgrupp för evenemang

or

   Konfigurationsgrupp f\u00f6r evenemang

but this does happen because my code adds one more backslash to the value because of using the npm package 'properties-reader'

here is my code :

const fs = require("fs");
const PropertiesReader = require("properties-reader");
const properties = PropertiesReader("./Language_sv.properties").getAllProperties();
console.log(properties);

anyone has a better idea to get all properties in on object

Language_sv.properties is the file has :

 calendar-event-group-configuration=Konfigurationsgrupp f\u00f6r 
 evenemang

I found another package called ('properties') does not have the issue with the one above but I do not know how i can get the object (obj) out side of the function

const fs = require("fs");
var prop = require ("properties");

prop.parse ("./Language_sv.properties", { path: true }, function (error, obj){
  if (error) return console.error (error);
  
  console.log (obj);
});

CodePudding user response:

You can use unescape

const property = "calendar-event-group-configuration=Konfigurationsgrupp f\u00f6r evenemang"

console.log(unescape(property));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Your problem is that properties-reader does not understand unicode characters. One way to go around it is to postprocess the property values after it was read.

const fs = require("fs");
const PropertiesReader = require("properties-reader");
const properties = PropertiesReader("./Language_sv.properties", 'utf-8').getAllProperties();
console.log(properties);
for(let i in properties){
    properties[i] = properties[i].replace('"','\\"')
    properties[i] = decodeURIComponent(
        JSON.parse('"'  properties[i]   '"')
    )
}
console.log(properties);

Here I covert property value into a string enclosed within quotes, and then parse it with JSON.parse. It parses the escaped backslash properly. And decodeURIComponent coverts unicode escape sequence to the character.

  • Related