Home > Back-end >  how to strip newline character from JSON data structure in Python3
how to strip newline character from JSON data structure in Python3

Time:12-10

I use this code to create a json data package. The datapackage gets a newline character appended: 'fields': {'time': '31.495\n'} How do I get rid of this \n?

import subprocess, signal, os, pylibmc, time, datetime

# Send network ping delay time to influxdb
cmd = "ping -c 1 1.0.0.1 | tail -1| awk '{print $4}' | cut -d '/' -f 2" # pylint: disable=line-too-long
data=subprocess.check_output(cmd, shell=True).decode("utf-8")
print(data)

stamp=time.ctime()
print(id)
print("[%s] Time: %s" % (stamp, data))
print(data)
#Create the JSON data structure
data = [
      {
        "measurement": "ping_delay",
        "tags": {
        "location": location,
        },
        "time": stamp,
        "fields": {
        "delay" : data,
       }
      }
    ]
# Send the JSON data to InfluxDB
print(data)

CodePudding user response:

You can make use of the strip() function in python.

    # Other code
    "time" : stamp.strip('\n')
    # Other code

CodePudding user response:

I don't completely understand your example since you don't have time element within fields. But anyway you can use rstrip to strip whitespaces from the end of a variable. https://docs.python.org/3/library/stdtypes.html#str.rstrip

  • Related