Programing

JSON ValueError : 예상 속성 이름 : 줄 1 열 2 (문자 1)

crosscheck 2020. 9. 11. 07:28
반응형

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.loadsjson 속성에는 큰 따옴표 만 허용합니다 .

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

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.


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

참고URL : https://stackoverflow.com/questions/25707558/json-valueerror-expecting-property-name-line-1-column-2-char-1

반응형