0

I have the following output from a script

{"emeter":{"get_realtime":{"current":0.501730,"voltage":240.819788,"power":70.455025,"total":1.798000,"err_code":0}}}

I need to convert it to this format for prometheus exporter collector:

current 0.53
voltage 234
power 84.04
total 0.92

Suggestions?

John1024
  • 109,961
  • 14
  • 137
  • 171
anarchist
  • 383
  • 2
  • 5
  • 18
  • Why did the voltage change from 240.82 in the input to 234 in the output? – John1024 Jan 10 '18 at 22:28
  • 1
    possible duplicate of https://stackoverflow.com/questions/1955505/parsing-json-with-unix-tools – victor Jan 10 '18 at 22:32
  • the voltage changed because the readings were taken at different times, it is by default like 240.23423 but i need it displayed as 240 – anarchist Jan 11 '18 at 08:31

1 Answers1

0
  1. Get the inner object - consider my_obj is your object after parsing your JSON
  2. Get your objects' keys as an array of string with Object.keys()
  3. Ignore "err_code" with filter method of Array
  4. I used console log to log the output - no idea how you wanted it but i guess you can easily figure it out now

var my_obj = {
  "emeter": {
    "get_realtime": {
      "current": 0.501730,
      "voltage": 240.819788,
      "power": 70.455025,
      "total": 1.798000,
      "err_code": 0
    }
  }
}
var inner = my_obj.emeter.get_realtime;
var innerKeys = Object.keys(inner);
innerKeys.filter(k => k !== "err_code")
  .forEach(k => console.log(k, inner[k]));
Tomasz Bubała
  • 2,093
  • 1
  • 11
  • 18