Python JSON ValueError:期望属性名称:第 1 行第 2 列(字符 1)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25707558/
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-18 23:32:03  来源:igfitidea点击:

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

pythonjsonpymongo

提问by dredbound

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

我在使用 json.loads 转换为 dict 对象时遇到问题,我无法弄清楚我做错了什么。我运行这个的确切错误是

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.

但我不知道该怎么做才能解决它。任何意见,将不胜感激。

采纳答案by Yep_It's_Me

json.loadswill load a json string into a python dict, json.dumpswill dump a python dictto a json string, for example:

json.loads将 json 字符串加载到 python 中dictjson.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}'

So that line is incorrect since you are trying to loada python dict, and json.loadsis expecting a valid json stringwhich should have <type 'str'>.

所以这行不正确,因为你正试图load蟒蛇dict,并json.loads期待一个有效的json string应该有<type 'str'>

So if you are trying to load the json, you should change what you are loading to look like the json_stringabove, 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?

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

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

你也不需要u在你的字符串之前指定,正如注释中提到的@Cld。

回答by Samuel Dauzon

I encountered another problem that returns the same error.

我遇到了另一个返回相同错误的问题。

Single quote issue

单引号问题

I used a json string with single quotes:

我使用了带单引号的 json 字符串:

{
    'property': 1
}

But json.loadsaccepts only double quotes for json properties:

json.loads只接受 json 属性的双引号

{
    "property": 1
}

Final comma issue

最后逗号问题

json.loadsdoesn't accept a final comma:

json.loads不接受最后一个逗号:

{
  "property": "text", 
  "property2": "text2",
}

Solution: astto solve single quote and final comma issues

解决方案:ast解决单引号和结尾逗号问题

You can use ast(part of standard library for both Python 2 and 3) for this processing. Here is an example :

您可以使用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"}

Using astwill 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.

Usingast将通过插入像 Python 字典这样的 JSON 来防止您出现单引号和最后的逗号问题(因此您必须遵循 Python 字典语法)。这是eval()文字结构函数的一个非常好的和安全的替代方案。

Python documentationwarned us of using large/complex string :

Python 文档警告我们不要使用大/复杂字符串:

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.

警告 由于 Python 的 AST 编译器中的堆栈深度限制,使用足够大/复杂的字符串可能会导致 Python 解释器崩溃。

json.dumps with single quotes

json.dumps 带单引号

To use json.dumpswith single quotes easily you can use this code:

json.dumps轻松使用单引号,您可以使用以下代码:

import ast
import json

data = json.dumps(ast.literal_eval(json_data_single_quote))

astdocumentation

ast文件

ast Python 3 doc

ast Python 3 文档

ast Python 2 doc

ast Python 2 文档

Tool

工具

If you frequently edit JSON, you may use CodeBeautify. It helps you to fix syntax error and minify/beautify JSON.

如果您经常编辑 JSON,则可以使用CodeBeautify。它可以帮助您修复语法错误并缩小/美化 JSON。

I hope it helps.

我希望它有帮助。

回答by Vinay Pande

  1. replace all single quotes with double quotes
  2. replace 'u"' from your strings to '"' ... so basically convert internal unicodes to strings before loading the string into json
  1. 用双引号替换所有单引号
  2. 将字符串中的 'u"' 替换为 '"' ...因此,在将字符串加载到 json 之前,基本上将内部 unicode 转换为字符串
>> strs = "{u'key':u'val'}"
>> strs = strs.replace("'",'"')
>> json.loads(strs.replace('u"','"'))

回答by Rishabh Agrahari

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:

所有其他答案可能会回答您的查询,但我遇到了同样的问题,这是由于,我在 json 字符串末尾添加的杂散问题,如下所示:

{
 "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.

希望这有帮助!干杯。

回答by xin.chen

used ast, example

使用 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'}]