问题:JSON ValueError:期望的属性名称:第1行第2列(字符1)
我在使用json.loads转换为dict对象时遇到麻烦,我无法弄清楚我在做什么错。我得到的确切错误是
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)
我很确定错误发生在第二行到最后一行
jsonTweet=json.loads({u'favorited': False, u'contributors': None})
但我不知道该如何解决。任何意见,将不胜感激。
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.
回答 0
json.loads
将json字符串加载到python中dict
,json.dumps
将python转储dict
到json字符串中,例如:
>>> 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
应该有一个有效的python <type 'str'>
。
因此,如果您尝试加载json,则应更改要加载的内容,使其类似于json_string
上面的内容,否则应将其转储。根据给定的信息,这只是我的最佳猜测。您要完成什么?
另外,您也不需要u
在字符串前指定,就像注释中提到的@Cld一样。
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.
回答 1
我遇到另一个返回相同错误的问题。
单引号
我使用带单引号的json字符串:
{
'property': 1
}
但是json.loads
只接受json属性的双引号:
{
"property": 1
}
最终逗号问题
json.loads
不接受最终逗号:
{
"property": "text",
"property2": "text2",
}
解决方案:ast
解决单引号和最终逗号问题
您可以使用ast
(Python 2和3的标准库的一部分)进行此处理。这是一个例子:
import ast
# ast.literal_eval() return a dict object, we must use json.dumps to get JSON string
import json
# Single quote to double with ast.literal_eval()
json_data = "{'property': 'text'}"
json_data = ast.literal_eval(json_data)
print(json.dumps(json_data))
# Displays : {"property": "text"}
# ast.literal_eval() with double quotes
json_data = '{"property": "text"}'
json_data = ast.literal_eval(json_data)
print(json.dumps(json_data))
# Displays : {"property": "text"}
# ast.literal_eval() with final coma
json_data = "{'property': 'text', 'property2': 'text2',}"
json_data = ast.literal_eval(json_data)
print(json.dumps(json_data))
# Displays : {"property2": "text2", "property": "text"}
使用ast
会像Python字典一样插入JSON,从而避免出现单引号和最终逗号问题(因此,您必须遵循Python字典语法)。它是eval()
文字结构函数的一种非常不错且安全的替代方法。
Python文档警告我们使用大/复杂字符串:
警告由于Python AST编译器中的堆栈深度限制,使用足够大/复杂的字符串可能会使Python解释器崩溃。
带有单引号的json.dumps
要json.dumps
轻松使用单引号,可以使用以下代码:
import ast
import json
data = json.dumps(ast.literal_eval(json_data_single_quote))
ast
文件资料
ast Python 3 doc
ast Python 2文档
工具
如果您经常编辑JSON,则可以使用CodeBeautify。它可以帮助您修复语法错误并缩小/美化JSON。
希望对您有所帮助。
I encountered another problem that returns the same error.
Single quote issue
I used a json string with single quotes :
{
'property': 1
}
But json.loads
accepts only double quotes for json properties :
{
"property": 1
}
Final comma issue
json.loads
doesn’t accept a final comma:
{
"property": "text",
"property2": "text2",
}
Solution: ast
to solve single quote and final comma issues
You can use ast
(part of standard library for both Python 2 and 3) for this processing. Here is an example :
import ast
# ast.literal_eval() return a dict object, we must use json.dumps to get JSON string
import json
# Single quote to double with ast.literal_eval()
json_data = "{'property': 'text'}"
json_data = ast.literal_eval(json_data)
print(json.dumps(json_data))
# Displays : {"property": "text"}
# ast.literal_eval() with double quotes
json_data = '{"property": "text"}'
json_data = ast.literal_eval(json_data)
print(json.dumps(json_data))
# Displays : {"property": "text"}
# ast.literal_eval() with final coma
json_data = "{'property': 'text', 'property2': 'text2',}"
json_data = ast.literal_eval(json_data)
print(json.dumps(json_data))
# Displays : {"property2": "text2", "property": "text"}
Using ast
will prevent you from single quote and final comma issues by interpet the JSON like Python dictionnary (so you must follow the Python dictionnary syntax). It’s a pretty good and safely alternative of eval()
function for literal structures.
Python documentation warned us of using large/complex string :
Warning It is possible to crash the Python interpreter with a
sufficiently large/complex string due to stack depth limitations in
Python’s AST compiler.
json.dumps with single quotes
To use json.dumps
with single quotes easily you can use this code:
import ast
import json
data = json.dumps(ast.literal_eval(json_data_single_quote))
ast
documentation
ast Python 3 doc
ast Python 2 doc
Tool
If you frequently edit JSON, you may use CodeBeautify. It helps you to fix syntax error and minify/beautify JSON.
I hope it helps.
回答 2
- 用双引号替换所有单引号
- 将字符串中的’u“’替换为’”’…因此,在将字符串加载到json之前,基本上将内部unicodes转换为字符串
>> strs = "{u'key':u'val'}"
>> strs = strs.replace("'",'"')
>> json.loads(strs.replace('u"','"'))
- replace all single quotes with double quotes
- replace ‘u”‘ from your strings to ‘”‘ … so basically convert internal unicodes to strings before loading the string into json
>> strs = "{u'key':u'val'}"
>> strs = strs.replace("'",'"')
>> json.loads(strs.replace('u"','"'))
回答 3
所有其他答案都可以回答您的查询,但是我遇到了同样的问题,这是由于,
我在json字符串的末尾添加了这样的杂散:
{
"key":"123sdf",
"bus_number":"asd234sdf",
}
当我,
像这样删除多余的东西时,我终于使它工作了:
{
"key":"123sdf",
"bus_number":"asd234sdf"
}
希望有帮助!干杯。
All other answers may answer your query, but I faced same issue which was due to stray ,
which I added at the end of my json string like this:
{
"key":"123sdf",
"bus_number":"asd234sdf",
}
I finally got it working when I removed extra ,
like this:
{
"key":"123sdf",
"bus_number":"asd234sdf"
}
Hope this help! cheers.
回答 4
使用ast,例如
In [15]: a = "[{'start_city': '1', 'end_city': 'aaa', 'number': 1},\
...: {'start_city': '2', 'end_city': 'bbb', 'number': 1},\
...: {'start_city': '3', 'end_city': 'ccc', 'number': 1}]"
In [16]: import ast
In [17]: ast.literal_eval(a)
Out[17]:
[{'end_city': 'aaa', 'number': 1, 'start_city': '1'},
{'end_city': 'bbb', 'number': 1, 'start_city': '2'},
{'end_city': 'ccc', 'number': 1, 'start_city': '3'}]
used ast,
example
In [15]: a = "[{'start_city': '1', 'end_city': 'aaa', 'number': 1},\
...: {'start_city': '2', 'end_city': 'bbb', 'number': 1},\
...: {'start_city': '3', 'end_city': 'ccc', 'number': 1}]"
In [16]: import ast
In [17]: ast.literal_eval(a)
Out[17]:
[{'end_city': 'aaa', 'number': 1, 'start_city': '1'},
{'end_city': 'bbb', 'number': 1, 'start_city': '2'},
{'end_city': 'ccc', 'number': 1, 'start_city': '3'}]
回答 5
我遇到的另一种情况是,当我使用echo
JSON将其通过管道传递到python脚本中,并且不小心将JSON字符串用双引号引起来时:
echo "{"thumbnailWidth": 640}" | myscript.py
请注意,JSON字符串本身带有引号,我应该这样做:
echo '{"thumbnailWidth": 640}' | myscript.py
由于这是,这是获得什么python脚本:{thumbnailWidth: 640}
; 双引号已被有效删除。
A different case in which I encountered this was when I was using echo
to pipe the JSON into my python script and carelessly wrapped the JSON string in double quotes:
echo "{"thumbnailWidth": 640}" | myscript.py
Note that the JSON string itself has quotes and I should have done:
echo '{"thumbnailWidth": 640}' | myscript.py
As it was, this is what the python script received: {thumbnailWidth: 640}
; the double quotes were effectively stripped.