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})
그러나 나는 그것을 고치기 위해 무엇을 해야할지 모른다. 조언을 주시면 감사하겠습니다.
json.loads
파이썬으로 JSON 문자열을로드 dict
, json.dumps
파이썬을 덤프 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
파이썬을 시도하고 있기 때문에 올바르지 dict
않으며, 있어야 json.loads
할 유효한 json string
것을 기대하고 있습니다 <type 'str'>
.
따라서 json을로드하려는 경우로드중인 내용을 json_string
위와 같이 변경 하거나 덤프해야합니다. 이것은 주어진 정보에서 내 최선의 추측입니다. 달성하려는 것이 무엇입니까?
또한 u
주석에서 @Cld가 언급했듯이 문자열 앞에 를 지정할 필요가 없습니다 .
동일한 오류를 반환하는 다른 문제가 발생했습니다.
작은 따옴표 문제
작은 따옴표가 있는 json 문자열을 사용했습니다 .
{
'property': 1
}
그러나 json.loads
json 속성에는 큰 따옴표 만 허용합니다 .
{
"property": 1
}
마지막 쉼표 문제
json.loads
마지막 쉼표를 허용하지 않습니다.
{
"property": "text",
"property2": "text2",
}
솔루션 : ast
작은 따옴표 및 마지막 쉼표 문제 해결
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
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.
- 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"','"'))
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.
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'}]
'Programing' 카테고리의 다른 글
명령 줄에서 Gradle을 통해 장치에 배포 할 수 있습니까? (0) | 2020.09.11 |
---|---|
C # 구문-문자열을 쉼표로 배열로 분할, 일반 목록으로 변환 및 역순 (0) | 2020.09.11 |
문자열을 반환하는 값에 자바 스크립트 (jquery)로 정수 값을 추가하려면 어떻게해야합니까? (0) | 2020.09.11 |
존재하지 않는 경우 mysql 사용자 생성 (0) | 2020.09.11 |
아무것도 반환하지 않는 함수를 만드는 방법 (0) | 2020.09.10 |