Skip to content

Instantly share code, notes, and snippets.

@johnallen3d
Last active June 13, 2018 01:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnallen3d/61e2a165a5e13218c7621f6ba31a11fd to your computer and use it in GitHub Desktop.
Save johnallen3d/61e2a165a5e13218c7621f6ba31a11fd to your computer and use it in GitHub Desktop.
Take the formatted output of `mpc status` and convert it into JSON...

MPC Status as JSON

Take the formatted output of mpc status and convert it to JOSN.

Why?

I'm running Übersicht and made some tweaks to another users mpd widget. The existing implementation used awk and echoed values concatenating them together with @. Then in JS/Coffeescript parsing the string on @ and accessing the values based on expected position. It occurred to me it would be more convenient to use JSON in Übersicht so I created this.

Usage

By default mpc status return something like this:

❯  mpc status
I'm With Her - Ain't The Fine
[paused]  #3/12   2:38/3:09 (83%)
volume: 64%   repeat: off   random: off   single: off   consume: off

This script will return results like this:

❯  ./mpc-status-json.sh
{
  "artist":             "I'm With Her",
  "song":               "Ain't The Fine",
  "elapsed":            "2:38/3:09",
  "currentTime":        "2:38",
  "trackLength":        "3:09",
  "currentTrackNumber": "3",
  "totalTrackCount":    "12",
  "status":             "[paused]",
  "trackCount":         "",
  "volume":             "64%"
}

Then in a JS environment simply parse the resulting string. For example in Übersicht:

update: (output, domEl) ->
  details = JSON.parse(output);
  
  $(domEl).find('#artist').text(details.artist)
  ...
#! /usr/bin/env bash
STATUS="$(/usr/local/bin/mpc status)"
if [ $(echo "$STATUS" | wc -l | tr -d ' ') == "1" ]; then
status="[empty]"
else
artist=$(echo "$STATUS" | awk -F" - " 'NR==1{print $1}')
song=$(echo "$STATUS" | awk -F" - " 'NR==1{print $2}')
status=$(echo "$STATUS" | awk 'NR==2{print $1}')
track_data=$(echo "$STATUS" | awk 'NR==2{print $2}')
current_track_number=$(echo "$track_data" | awk -F"/" '{print $1}')
total_track_count=$(echo "$track_data" | awk -F"/" '{print $2}')
elapsed=$(echo "$STATUS" | awk 'NR==2{print $3}')
current_time=$(echo "${elapsed}" | awk -F"/" '{print $1}')
track_length=$(echo "${elapsed}" | awk -F"/" '{print $2}')
volume=$(
echo "$STATUS" \
| awk -F":" 'NR==3{print $2}' \
| awk '{print $1}'
)
fi
echo "{
\"artist\": \"${artist}\",
\"song\": \"${song}\",
\"elapsed\": \"${elapsed}\",
\"currentTime\": \"${current_time}\",
\"trackLength\": \"${track_length}\",
\"currentTrackNumber\": \"${current_track_number/\#/}\",
\"totalTrackCount\": \"${total_track_count}\",
\"status\": \"${status}\",
\"volume\": \"${volume}\"
}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment