[Solved] Convert comma separated json list to .map file

Hi guys,

I’m looking for a solution to automatically convert a simple json string to a map file everytime the string item changes.

The Squeezebox Binding provides a comma separated json list which includes the favoritesList from the the server. I’m using a .map file for display purposes in MainUI.

But everytime I change the list on the server I have to manually update the .map file.

My idea is to write a rule which keeps them in sync

  • check the favoritesList item for changes
  • on change take the item string and convert "commata" to "linebrakes"
  • overwrite the existing .map file with the new created list

the first point is a nobrainer…

but I’m not sure how to convert json list to linebrakes and couldn’t find any attemps on the forum search.

and it’s also not so clear to me how to manipulate files through rules. I’m not sure but I think rulesDSL is not capable of that - maybe JSscripting. Or maybe I have to use a bash script to manipulate the json and save the .map file??

Would be very nice to get some help on that, thanks :wink:

in short:

convert this

0=ListItem1,1=ListItem2,2=ListItem3

to this

0=ListItem1
1=ListItem2
2=ListItem3

and save it to a .map file in /etc/openhab/transform/

Two problems to solve here:

  1. convert the commas in string „a,b,c“ to newlines
  2. write the result to a file

For 1. have a look at javascript - Split string with commas to new line - Stack Overflow . Basically in a Javascript rule:
var multiLineString = stringInOneLine.split(",").join("\n")

For 2. there was a discussion how to do that in openHAB recently here: Need help in Script to Read or Parse a File - #7 by Fleck

Not a complete solution, but hopefully it is enough to get started :slight_smile:

1 Like

thanx a ton :wink: I think this is what I was looking for in general…

I’ll post my results here!

Ok here’s my (working) result:

const {log, rules, triggers} = require("openhab");

rules.JSRule({
  name: "Script - Update Favorites Map",
  description: "update .map file for squeezeserver favorites list",
  triggers: [
    triggers.ItemStateUpdateTrigger('SqueezeServerListFavorite')
  ],
  execute: data => {
    const favList = items.getItem("SqueezeServerListFavorite");
    
    var favListjson = favList.state;
    var mapString = favListjson.split(",").join("\n");

    var FileWriter = Java.type('java.io.FileWriter');
    var BufferedWriter = Java.type('java.io.BufferedWriter');

    var outFile = new FileWriter("/etc/openhab/transform/squeezefav.map");
    var out = new BufferedWriter(outFile);
    out.write(mapString);
    out.newLine();
    out.flush();
    out.close();
  },
  tags: []
});

thanks again for your help :+1:
I’m really happy with this solution :wink: