简体   繁体   English

Python:如何在list / json中保留单引号

[英]Python: How to keep single quotes in list/json

I am creating a rest api in Python using flask and using curl command to test my function. 我正在使用flask和使用curl命令在Python中创建rest api,以测试我的功能。

Curl Command: 卷曲命令:

$ curl -X POST 
  -H "Content-Type:application/json"
  -d '{"keyword": "2''binders", "country": "xyz", "frequency": "1","url":"www.example.com"}' \
  http://127.0.0.1:5000/google

Output: 输出:

'['New Request', u'**2binders**', u'xyz', u'www.example.com', u'1']'

As you can see I am passing inches in json 2''binders but in my list it is removing that. 如您所见,我在json 2'' 2''binders传递了英寸,但在我的列表中它删除了它。

Edit: 编辑:

Python: json = request.get_json(force=True) print json Python: json = request.get_json(force=True) print json

In your curl command, try using "keyword": "2\\'\\'binders" . 在curl命令中,尝试使用"keyword": "2\\'\\'binders" You need to escape the single quotes inside the -d parameter, because you're using single quotes around the -d parameter. 您需要在-d参数内转义单引号,因为您正在-d参数周围使用单引号。

The shell is getting confused and thinking you are wanting string concatenation. 外壳变得混乱,以为您想要字符串连接。 Eg the shell is seeing 'abc''def' and interpreting that as 'abcdef' . 例如,shell看到'abc''def'并将其解释为'abcdef'

If you try to json.dumps the dictionary itself: 如果您尝试json.dumps字典本身:

>>> s = json.dumps(d)
>>> 
>>> s
'{"url": "www.example.com", "country": "xyz", "frequency": "1", "keyword": "2\'\'binders"}'
                                                                              ^ ^

You will see that it will automatically escape ' , as mentioned in the previous answer, escaping it should do the trick to you: 您将看到它会自动转义' ,如上一个答案中所述,转义它应该可以解决您的问题:

>>> json.loads(s)
{u'url': u'www.example.com', u'country': u'xyz', u'frequency': u'1', u'keyword': u"2''binders"} #Single quote is back

Got it!!! 得到它了!!!

curl -X POST -d '{"keyword": "2'\\'''\\''binders", "country": "xyz", "frequency": "1","url":" http://www.example.com/ "}' http://127.0.0.1:5000/google -H "Content-Type:application/json" curl -X POST -d'{“ keyword”:“ 2'\\'''\\” binders“,” country“:” xyz“,” frequency“:” 1“,” url“:” http:// www.example.com/ “}” http://127.0.0.1:5000/google -H “内容类型:应用程序/ JSON”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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