简体   繁体   中英

how to strip newline character from JSON data structure in Python3

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)

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM