1

This is a difficult problem to explain. I have a string that looks like "system.cpu.total.pct" that I'm pulling from a json configuration file. This particular format is required elsewhere in my program so I cannot change it.

This "system.cpu.total.pct" specifies what field I'm interested in snagging out of metricbeat (in Elasticsearch).

I need to convert this into a list address (? is that what to call it ?) so that I can snag stuff out of an array of database results I'm calling 'rawData'. Right now I'm doing this:

if sourceSet == "system.cpu.total.pct":
    dataArray.append(rawData['hits']['hits'][thisRecord]["_source"]['system']['cpu']['total']['pct'])

But that's no good, obviously, because the result is hard-coded.

How can I instead write something like

dataArray.append(rawData['hits']['hits'][thisRecord]["_source"]["system.cpu.total.pct"])

that will work for any arbitrary string?

Any suggestions? Thank you!

  • 1
    Hi, could you please clarify what the code would actually do? `system.cpu.total.pct` would be transformed into what? – Joseph Chotard Mar 19 '20 at 14:20
  • "that's no good, obviously, because the result is hard-coded" - you could use `query_str.split('.')` to get the elements and then iterate over calls to the dictionary's `get()` method. – Brian Cain Mar 19 '20 at 14:20
  • I have duplicate links for PHP and JavaScript, the same general approach should work for Python: [PHP](https://stackoverflow.com/questions/27929875/how-to-write-getter-setter-to-access-multi-level-array-by-key-names) [JS](https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-and-arays-by-string-path) – Barmar Mar 19 '20 at 14:47

1 Answers1

1

you can use:

if sourceSet == "system.cpu.total.pct":
    d = rawData['hits']['hits'][thisRecord]["_source"]
    for t in sourceSet.split('.'):
        d = d[t]

    dataArray.append(d)
kederrac
  • 16,819
  • 6
  • 32
  • 55