Python 的 json.load(sys.stdin) 让我 u'...' 而不是字符串周围的双引号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34590412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:14:20  来源:igfitidea点击:

Python's json.load(sys.stdin) gets me u'...' instead of double quotes around Strings

pythonjsonparse-platform

提问by Marian Pa?dzioch

When I do:

当我做:

import sys, json;
import requests

headers = {'Content-Type': 'application/json',
       'X-Parse-Application-Id': '...',
       'X-Parse-REST-API-Key': '...'}

data = json.load(sys.stdin)
for station in data["data"]:
    print station
    res = requests.post('https://api.parse.com/1/classes/test4', data=station, headers=headers)

I get

我得到

{u'city': u'London',
...
}

And it's not a valid Json as when I try to POST it to Parse.com I'm getting

它不是有效的 Json,因为当我尝试将它发布到 Parse.com 时,我得到了

{"code":107,"error":"invalid JSON"}

and any JSON validator gives me Error:Strings should be wrapped in double quotes.

任何 JSON 验证器都会给我 Error:Strings should be wrapped in double quotes.

How to make a valid JSON of the data?

如何制作有效的 JSON data

采纳答案by m fran

printwill just print python's representation of the object you are passing (which you deserialized with json.load). Try this:

print将只打印 Python 对您正在传递的对象的表示(您使用 反序列化json.load)。尝试这个:

import sys, json;
data = json.load(sys.stdin)
for station in data["data"]:
    print(json.dumps(station))

json.dumpsserializes a python object back to json.

json.dumps将 python 对象序列化回 json。

回答by Daniel Roseman

You've misunderstood what json.loaddoes: it deserializesfrom JSON, ie it creates Python objects from JSON strings.

你误解了什么json.load:它从 JSON反序列化,即它从 JSON 字符串创建 Python 对象。

But I can't really understand what you're doing; if you already have JSON being passed in from stdin, why are you trying to convert it at all? Pass it straight on to your API.

但我真的无法理解你在做什么;如果您已经从 stdin 传入了 JSON,那么您为什么要尝试转换它?将其直接传递给您的 API。