1

A really simple noob question. How do I place variables in this json_body variable? The problem is with all the quotation marks. I can't use the .format string method for this as the json_body variable isn't holding a simple string.

from influxdb import InfluxDBClient

json_body = [
{
    "measurement": "cpu_load_short",
    "tags": {
        "host": "server01",
        "region": "us-west"
    },
    "time": "2009-11-10T23:00:00Z",
    "fields": {
        "value": 0.64
    }
}
] 
client = InfluxDBClient('localhost', 8086, 'root', 'root', 'example')
client.create_database('example')
client.write_points(json_body)

Source: https://github.com/influxdata/influxdb-python#examples

So, for example, how do I get a variable in there, e.g.

"value": 0.64

to:

"value": variable_name?

In the example code, all values are hard-coded.

Malte
  • 337
  • 1
  • 11

1 Answers1

0

The right way is to build the dictionary as a Python object, using your variables, then use json.dumps.

For example

import json
x = 42
d = {'answer': x}
print(json.dumps(d))

This prints

{"answer": 42}

As you surmised in your question, you must not use string interpolation because the values you interpolate may contain quotes. Good observation!

EDIT

You mentioned in a comment that you had a larger object. Perhaps you want to do something like this?

def create_json_body_for_value(value):
    return json.dumps([
        {
            "measurement": "cpu_load_short",
            "tags": {
                "host": "server01",
                "region": "us-west"
            },
            "time": "2009-11-10T23:00:00Z",
            "fields": {
                "value": value
            }
        }
    ])
Ray Toal
  • 86,166
  • 18
  • 182
  • 232
  • Hi Ray, thanks for that! Could I clarify a bit? The delta between your sample code and my json_body variable is too big for me right now. – Malte Sep 25 '18 at 02:57
  • I can't really type out my sample code in this comment box. But I just tried and it didn't work as expected. – Malte Sep 25 '18 at 02:58
  • Feel free to clarify by adding to your question. I just added something to my answer that _might_ help. – Ray Toal Sep 25 '18 at 04:53