sourcetip

json 문자열을 python 개체로 변환

fileupload 2023. 3. 29. 21:46
반응형

json 문자열을 python 개체로 변환

json 문자열(예를 들어 twitter 검색 json 서비스에서 반환된 문자열 등)을 단순한 문자열 객체로 변환할 수 있습니까?다음은 json 서비스에서 반환된 데이터의 간단한 예입니다.

{
results:[...],
"max_id":1346534,
"since_id":0,
"refresh_url":"?since_id=26202877001&q=twitter",
.
.
.
}

어떤 식으로든 결과를 변수, 를 들어 obj에 저장한다고 합시다.다음과 같은 적절한 값을 얻으려고 합니다.

print obj.max_id
print obj.since_id

사용해보았습니다.simplejson.load()그리고.json.load()근데 그게 잘못됐어'str' object has no attribute 'read'

사용해보았습니다.simplejson.load()그리고.json.load()근데 그게 잘못됐어'str' object has no attribute 'read'

문자열에서 로드하려면json.loads()('s'에 주의해 주세요.

보다 효율적으로는 응답을 문자열로 읽는 단계를 건너뛰고 응답을 에 전달합니다.json.load().

데이터가 파일인지 문자열인지 모를 경우...사용하다

import StringIO as io
youMagicData={
results:[...],
"max_id":1346534,
"since_id":0,
"refresh_url":"?since_id=26202877001&q=twitter",
.
.
.
}

magicJsonData=json.loads(io.StringIO(str(youMagicData)))#this is where you need to fix
print magicJsonData
#viewing fron the center out...
#youMagicData{}>str()>fileObject>json.loads
#json.loads(io.StringIO(str(youMagicData))) works really fast in my program and it would work here so stop wasting both our reputation here and stop down voting because you have to read this twice 

https://docs.python.org/3/library/io.html#text-i-o 에서

python 빌트인 라이브러리의 json.dll은 파일 오브젝트를 필요로 하며 전달된 내용을 체크하지 않습니다.따라서 파일 오브젝트는 read를 호출할 때만 데이터를 포기하기 때문에 전달된 내용에 대해 read 함수를 호출합니다.따라서 내장 문자열 클래스에는 읽기 기능이 없기 때문에 래퍼가 필요합니다.그래서 스트링IO. 문자열IO 함수는 간단히 말해 문자열 클래스와 파일 클래스를 하위 분류하고 내부 작업을 메싱하면 낮은 상세 리빌드 https://gist.github.com/fenderrex/843d25ff5b0970d7e90e6c1d7e4a06b1을 들을 수 있기 때문에 결국 RAM 파일을 쓰고 한 줄에 jsoning을 하는 것과 같습니다.

언급URL : https://stackoverflow.com/questions/3847399/convert-a-json-string-to-python-object

반응형