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

但是我不知道该怎么做才能修复它.任何建议都将不胜感激.

推荐答案

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}'

所以该行是不正确的,因为您正在try 对pythondict执行load操作,而json.loads期望的是有效的json string,而有效json string应该是<type 'str'>.

因此,如果您试图加载json,应该将加载的内容更改为上面的json_string,否则应该将其转储.根据给定的信息,这只是我最好的猜测.你想要完成的是什么?

Also you don't need to specify the u before your strings, as @Cld mentioned in the comments.

Json相关问答推荐

Google Page to JSON应用程序脚本出现CORS错误

如何使用表键名称GROUP_BY

如何编写MongoDB查询以返回数组数组

JSON API返回多个数组,需要帮助拼合数据以存储在SQL Server数据库表中

无法从JSON解析ZonedDateTime,但可以使用格式化程序很好地解析

VBA json按特定属性名称提取所有数据

Jolt-Json转换:通过引用标识符(而不是索引)设置值

删除 JOLT 中的方括号

将 json 转换为 jsonb 安全吗?

条件性构建/修改嵌套对象数组

将环境变量值从 yaml 传递到 json

使用 jq 将消息转换为数组

Golang 解组行为:字段过多?

如何迭代、动态加载我的表单输入元素,然后在 React 中的表单提交上检索输入值?

如何在 wso2 中组合 2 个 json 有效负载?

JSON 模式实际用于什么目的?

JSON 模式验证

Android JSON 库的性能和可用性比较

错误未判断调用put(K, V)作为原始类型java.util.HashMap的成员

强制 JSON.NET 在序列化 DateTime 时包含毫秒(即使 ms 组件为零)