json - Converting str to dict in python -
i got process's output using subprocess.popen() :
{ about: 'rrdtool xport json output', meta: { start: 1401778440, step: 60, end: 1401778440, legend: [ 'rta_min', 'rta_max', 'rta_average' ] }, data: [ [ null, null, null ], [ null, null, null ], [ null, null, null ], [ null, null, null ], [ null, null, null ], [ null, null, null ] ] }
it doesn't seem valid json me. have used ast.literal_eval()
, json.loads()
, no luck. can me in right direction ? in advance.
indeed, older versions of rddtool
export ecma-script, not json. according this debian bug report upgrading 1.4.8 should give proper json. see project changelog:
json output of xport json compilant keys being quoted now.
if cannot upgrade, have 2 options here; either attempt reformat apply quoting object key identifiers, or use parser that's more lenient , parses ecma-script object notation.
the latter can done external demjson
library:
>>> import demjson >>> demjson.decode('''\ ... { about: 'rrdtool xport json output', ... meta: { ... start: 1401778440, ... step: 60, ... end: 1401778440, ... legend: [ ... 'rta_min', ... 'rta_max', ... 'rta_average' ... ] ... }, ... data: [ ... [ null, null, null ], ... [ null, null, null ], ... [ null, null, null ], ... [ null, null, null ], ... [ null, null, null ], ... [ null, null, null ] ... ] ... }''') {u'about': u'rrdtool xport json output', u'meta': {u'start': 1401778440, u'step': 60, u'end': 1401778440, u'legend': [u'rta_min', u'rta_max', u'rta_average']}, u'data': [[none, none, none], [none, none, none], [none, none, none], [none, none, none], [none, none, none], [none, none, none]]}
repairing can done using regular expression; going assume identifiers on new line or directly after opening {
curly brace. single quotes in list have changed double quotes; work if there no embedded single quotes in values too:
import re import json yourtext = re.sub(r'(?:^|(?<={))\s*(\w+)(?=:)', r' "\1"', yourtext, flags=re.m) yourtext = re.sub(r"'", r'"', yourtext) data = json.loads(yourtext)
Comments
Post a Comment