如何从 Python3 中的 JSON 数据结构中去除换行符
how to strip newline character from JSON data structure in Python3
我使用此代码创建了一个 json 数据包。
数据包附加了一个换行符:'fields': {'time': '31.495\n'}
我如何摆脱这个\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 }' | 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)
您可以使用 python 中的 strip() 函数。
# Other code
"time" : stamp.strip('\n')
# Other code
我不完全理解您的示例,因为您在 fields
中没有 time
元素。但是无论如何,您可以使用 rstrip
从变量的末尾去除空格。 https://docs.python.org/3/library/stdtypes.html#str.rstrip
我使用此代码创建了一个 json 数据包。 数据包附加了一个换行符:'fields': {'time': '31.495\n'} 我如何摆脱这个\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 }' | 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)
您可以使用 python 中的 strip() 函数。
# Other code
"time" : stamp.strip('\n')
# Other code
我不完全理解您的示例,因为您在 fields
中没有 time
元素。但是无论如何,您可以使用 rstrip
从变量的末尾去除空格。 https://docs.python.org/3/library/stdtypes.html#str.rstrip