Search code examples
pythonjsonpymongo

JSON ValueError: Expecting property name: line 1 column 2 (char 1)


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)

Here is my code:

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.


Solution

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

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

    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?

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