developer tip

JSON의 작은 따옴표와 큰 따옴표

optionbox 2020. 9. 2. 17:44
반응형

JSON의 작은 따옴표와 큰 따옴표


내 코드 :

import simplejson as json

s = "{'username':'dfdsfdsf'}" #1
#s = '{"username":"dfdsfdsf"}' #2
j = json.loads(s)

#1 정의가 잘못되었습니다

#2 정의가 맞다

파이썬에서는 작은 따옴표 따옴표를 바꿀 수 있다고 들었습니다 . 누구든지 나에게 이것을 설명 할 수 있습니까?


JSON 구문 은 Python 구문 이 아닙니다. JSON에는 문자열에 큰 따옴표가 필요합니다.


당신이 사용할 수있는 ast.literal_eval()

>>> import ast
>>> s = "{'username':'dfdsfdsf'}"
>>> ast.literal_eval(s)
{'username': 'dfdsfdsf'}

다음과 같이 큰 따옴표로 JSON을 덤프 할 수 있습니다.

import json

# mixing single and double quotes
data = {'jsonKey': 'jsonValue',"title": "hello world"}

# get string with all double quotes
json_string = json.dumps(data) 

demjson 은 또한 잘못된 json 구문 문제를 해결하는 데 좋은 패키지입니다.

pip install demjson

용법:

from demjson import decode
bad_json = "{'username':'dfdsfdsf'}"
python_dict = decode(bad_json)

편집하다:

demjson.decode손상된 json에 대한 훌륭한 도구이지만 json 데이터의 큰 양을 처리 할 때 ast.literal_eval더 나은 일치이며 훨씬 빠릅니다.


말했듯이 JSON은 Python 구문이 아닙니다. JSON에서 큰 따옴표를 사용해야합니다. 제작자는 프로그래머의인지 과부하를 완화하기 위해 허용 가능한 구문의 엄격한 하위 집합을 사용하는 것으로 유명합니다.


@Jiaaro가 지적한 것처럼 JSON 문자열 자체에 작은 따옴표가 포함되어 있으면 아래가 실패 할 수 있습니다. 사용하지 마세요. 작동하지 않는 예를 여기에 남겨 두었습니다.

JSON 문자열에 작은 따옴표가 없다는 것을 아는 것은 정말 유용 합니다. 예를 들어 브라우저 콘솔에서 복사하여 붙여 넣었습니다. 그런 다음 입력 할 수 있습니다.

a = json.loads('very_long_json_string_pasted_here')

작은 따옴표도 사용하면 깨질 수 있습니다.


나는 최근에 매우 유사한 문제에 대해 생각해 냈고 내 솔루션이 당신에게도 효과가 있다고 믿습니다. 다음과 같은 형식의 항목 목록이 포함 된 텍스트 파일이 있습니다.

["first item", 'the "Second" item', "thi'rd", 'some \\"hellish\\" \'quoted" item']

위의 내용을 파이썬 목록으로 구문 분석하고 싶었지만 입력을 신뢰할 수 없기 때문에 eval ()에 열중하지 않았습니다. 먼저 JSON을 사용해 보았지만 큰 따옴표 항목 만 허용하므로이 특정 경우에 대해 매우 간단한 어휘 분석기를 작성했습니다 (자신의 "stringtoparse"를 연결하면 출력 목록 : 'items').

#This lexer takes a JSON-like 'array' string and converts single-quoted array items into escaped double-quoted items,
#then puts the 'array' into a python list
#Issues such as  ["item 1", '","item 2 including those double quotes":"', "item 3"] are resolved with this lexer
items = []      #List of lexed items
item = ""       #Current item container
dq = True       #Double-quotes active (False->single quotes active)
bs = 0          #backslash counter
in_item = False #True if currently lexing an item within the quotes (False if outside the quotes; ie comma and whitespace)
for c in stringtoparse[1:-1]:   #Assuming encasement by brackets
    if c=="\\": #if there are backslashes, count them! Odd numbers escape the quotes...
        bs = bs + 1
        continue                    
    if (dq and c=='"') or (not dq and c=="'"):  #quote matched at start/end of an item
        if bs & 1==1:   #if escaped quote, ignore as it must be part of the item
            continue
        else:   #not escaped quote - toggle in_item
            in_item = not in_item
            if item!="":            #if item not empty, we must be at the end
                items += [item]     #so add it to the list of items
                item = ""           #and reset for the next item
            continue                
    if not in_item: #toggle of single/double quotes to enclose items
        if dq and c=="'":
            dq = False
            in_item = True
        elif not dq and c=='"':
            dq = True
            in_item = True
        continue
    if in_item: #character is part of an item, append it to the item
        if not dq and c=='"':           #if we are using single quotes
            item += bs * "\\" + "\""    #escape double quotes for JSON
        else:
            item += bs * "\\" + c
        bs = 0
        continue

누군가에게 유용하기를 바랍니다. 즐겨!


import ast 
answer = subprocess.check_output(PYTHON_ + command, shell=True).strip()
    print(ast.literal_eval(answer.decode(UTF_)))

나를 위해 작동


import json
data = json.dumps(list)
print(data)

위의 코드 스 니펫이 작동합니다.

참고 URL : https://stackoverflow.com/questions/4162642/single-vs-double-quotes-in-json

반응형