问题描述
下面是我的字符串,它使用以下代码打印出来-
Below is my string that is getting printed out with the below code -
jsonString = data.decode("utf-8")
print jsonString
下面是在控制台上打印出的字符串-
And below is the string that got printed out on the console -
{"description":"Script to check testtbeat of TEST 1 server.", "script":"#!/bin/bash\nset -e\n\nCOUNT=60 #number of 10 second timeouts in 10 minutes\nSUM_SYNCS=0\nSUM_SYNCS_BEHIND=0\nHOSTNAME=$hostname \n\nwhile [[ $COUNT -ge \"0\" ]]; do\n\necho $HOSTNAME\n\n#send the request, put response in variable\nDATA=$(wget -O - -q -t 1 http://$HOSTNAME:8080/heartbeat)\n\n#grep $DATA for syncs and syncs_behind\nSYNCS=$(echo $DATA | grep -oE 'num_syncs: [0-9]+' | awk '{print $2}')\nSYNCS_BEHIND=$(echo $DATA | grep -oE 'num_syncs_behind: [0-9]+' | awk '{print $2}')\n\necho $SYNCS\necho $SYNCS_BEHIND\n\n#verify conditionals\nif [[ $SYNCS -gt \"8\" && $SYNCS_BEHIND -eq \"0\" ]]; then exit 0; fi\n\n#decrement the counter\nlet COUNT-=1\n\n#wait another 10 seconds\nsleep 10\n\ndone\n"}
但是当我使用python json.loads
加载它时,如下所示-
But when I load this out using python json.loads
as shown below-
jStr = json.loads(jsonString)
我收到此错误-
ERROR Invalid control character at: line 1 column 202 (char 202)
我查看了char 202,但不知道为什么会引起问题?我的记事本++中的char 202是e
我猜是..或者可能我计算错了
I looked at char 202 but I have no idea why that is causing an issue? char 202 in my notepad++ is e
I guess.. Or may be I am calculating it wrong
有什么想法吗?我如何找出引起问题的原因.
Any idea what is wrong? How do I find out which one is causing problem.
更新:-
jsonString = {"description":"Script to check testtbeat of TIER 1 server.", "script":"#!/bin/bash\nset -e\n\nCOUNT=60 #number of 10 second timeouts in 10 minutes\nSUM_SYNCS=0\nSUM_SYNCS_BEHIND=0\nHOSTNAME=$hostname \n\nwhile [[ $COUNT -ge \"0\" ]]; do\n\necho $HOSTNAME\n\n#send the request, put response in variable\nDATA=$(wget -O - -q -t 1 http://$HOSTNAME:8080/heartbeat)\n\n#grep $DATA for syncs and syncs_behind\nSYNCS=$(echo $DATA | grep -oE 'num_syncs: [0-9]+' | awk '{print $2}')\nSYNCS_BEHIND=$(echo $DATA | grep -oE 'num_syncs_behind: [0-9]+' | awk '{print $2}')\n\necho $SYNCS\necho $SYNCS_BEHIND\n\n#verify conditionals\nif [[ $SYNCS -gt \"8\" && $SYNCS_BEHIND -eq \"0\" ]]; then exit 0; fi\n\n#decrement the counter\nlet COUNT-=1\n\n#wait another 10 seconds\nsleep 10\n\ndone\n"}
print jsonString[202]
出现以下错误-
KeyError: 202
推荐答案
如果将字符串作为字符串文字复制粘贴到Python源代码中,则会出现错误.在这种情况下,\n
被解释为单个字符(换行符).您可以改用原始字符串文字(r''
,使用三引号r'''..'''
以避免在字符串文字中转义"'
引号)来解决此问题.
You can get the error if you copy-paste the string into your Python source code as a string literal. In that case \n
is interpreted as a single character (newline). You can fix it by using raw-string literals instead (r''
, Use triple-quotes r'''..'''
to avoid escaping "'
quotes inside the string literal).
这篇关于带有Python json.loads的无效控制字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!