JSON ValueError:期望的属性名称:第1行第2列(字符1) [英] JSON ValueError: Expecting property name: line 1 column 2 (char 1)
问题描述
我在使用json.loads转换为dict对象时遇到了麻烦,我无法弄清楚自己在做什么错.运行此错误的确切原因是
I am having trouble using json.loads to convert to a dict object and I can't figure out what I'm doing wrong.The exact error I get running this is
ValueError: Expecting property name: line 1 column 2 (char 1)
这是我的代码:
from kafka.client import KafkaClient
from kafka.consumer import SimpleConsumer
from kafka.producer import SimpleProducer, KeyedProducer
import pymongo
from pymongo import MongoClient
import json
c = MongoClient("54.210.157.57")
db = c.test_database3
collection = db.tweet_col
kafka = KafkaClient("54.210.157.57:9092")
consumer = SimpleConsumer(kafka,"myconsumer","test")
for tweet in consumer:
print tweet.message.value
jsonTweet=json.loads(({u'favorited': False, u'contributors': None})
collection.insert(jsonTweet)
我很确定该错误发生在倒数第二行
I'm pretty sure that the error is occuring at the 2nd to last line
jsonTweet=json.loads({u'favorited': False, u'contributors': None})
但是我不知道该怎么办.任何建议将不胜感激.
but I do not know what to do to fix it. Any advice would be appreciated.
推荐答案
json.loads
将json字符串加载到python dict
中,json.dumps
会将python dict
转储到json字符串中,例如:
json.loads
will load a json string into a python dict
, json.dumps
will dump a python dict
to a json string, for example:
>>> json_string = '{"favorited": false, "contributors": null}'
'{"favorited": false, "contributors": null}'
>>> value = json.loads(json_string)
{u'favorited': False, u'contributors': None}
>>> json_dump = json.dumps(value)
'{"favorited": false, "contributors": null}'
因此该行是不正确的,因为您尝试使用load
python dict
,并且json.loads
期望有效的json string
应该具有<type 'str'>
.
So that line is incorrect since you are trying to load
a python dict
, and json.loads
is expecting a valid json string
which should have <type 'str'>
.
因此,如果您尝试加载json,则应更改要加载的内容,使其看起来像上面的json_string
,否则您应该将其转储.根据给定的信息,这只是我的最佳猜测.您要完成什么?
So if you are trying to load the json, you should change what you are loading to look like the json_string
above, or you should be dumping it. This is just my best guess from the given information. What is it that you are trying to accomplish?
您也不需要在字符串前指定u
,如注释中提到的@Cld.
Also you don't need to specify the u
before your strings, as @Cld mentioned in the comments.
这篇关于JSON ValueError:期望的属性名称:第1行第2列(字符1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!