Invalid control character with Python json.loads

后端 未结 3 959
别那么骄傲
别那么骄傲 2020-12-28 12:20

Below is my string that is getting printed out with the below code -

jsonString = data.decode(\"utf-8\")

print jsonString

And below is the

相关标签:
3条回答
  • 2020-12-28 12:33

    Escape your newlines.

    {"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      #dc1dbx1145.dc1.host.com\\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"}
    

    Works for me.

    Also, if you get an error like this in the future, a debugging technique you can use is to shorten the string to something that works and slowly add data until it doesn't.

    0 讨论(0)
  • 2020-12-28 12:44

    There is no error in your json text.

    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).

    0 讨论(0)
  • 2020-12-28 12:49

    The control character can be allowed inside a string as follows,

    json_str = json.loads(jsonString, strict=False)
    

    You can find this in the docs for python 2, or the docs for python 3

    If strict is false (True is the default), then control characters will be allowed inside strings. Control characters in this context are those with character codes in the 0–31 range, including '\t' (tab), '\n', '\r' and '\0'.

    0 讨论(0)
提交回复
热议问题