python으로 json 파싱하기...

조회수 8745회

다음과 같은 데이터가 굉장히 많이 있습니다.

20110312000116101|{"place":{"country_code":"US","url":"http:\/\/api.twitter.com\/1\/geo\/id\/5c62ffb0f0f3479d.json","bounding_box":{"type":"Polygon","coordinates":[[[-112.323663,33.29026],[-111.926242,33.29026],[-111.926242,33.892637],[-112.323663,33.892637]]]},"name":"Phoenix","place_type":"city","country":"United States","attributes":{},"id":"5c62ffb0f0f3479d","full_name":"Phoenix, AZ"},"user":{"follow_request_sent":null,"show_all_inline_media":false,"geo_enabled":true,"profile_link_color":"999999","url":"http:\/\/soundcloud.com\/reallilkris","following":null,"verified":false,"profile_sidebar_border_color":"000000","is_translator":false,"listed_count":2,"statuses_count":6200,"profile_use_background_image":true,"profile_background_color":"a30fa3","description":"\u2714Verihighed Account Lil Kris.Self Made G.Check out my music. ","contributors_enabled":false,"profile_background_image_url":"http:\/\/a0.twimg.com\/profile_background_images\/215449854\/IMG_0551_opt.JPG","created_at":"Mon Jun 28 07:17:06 +0000 2010","friends_count":270,"protected":false,"profile_image_url":"http:\/\/a1.twimg.com\/profile_images\/1267186210\/xnboor_normal.jpg","time_zone":"Pacific Time (US & Canada)","favourites_count":3,"profile_text_color":"ff0d0d","location":"Smokin Loud in Phx, AZ","name":"Lil Kris","notifications":null,"profile_sidebar_fill_color":"000000","screen_name":"RealLilKris","id":160466271,"id_str":"160466271","lang":"en","profile_background_tile":true,"utc_offset":-28800,"followers_count":268},"coordinates":{"type":"Point","coordinates":[-112.07301182,33.3952667]},"text":"Smokin hella trees tonight.","in_reply_to_status_id":null,"truncated":false,"source":"\u003Ca href=\"http:\/\/twitter.com\/\" rel=\"nofollow\"\u003ETwitter for iPhone\u003C\/a\u003E","favorited":false,"in_reply_to_screen_name":null,"in_reply_to_user_id":null,"created_at":"Sat Mar 12 05:01:15 +0000 2011","in_reply_to_status_id_str":null,"geo":{"type":"Point","coordinates":[33.3952667,-112.07301182]},"contributors":null,"retweeted":false,"id":46435564391641088,"in_reply_to_user_id_str":null,"id_str":"46435564391641088","entities":{"urls":[],"user_mentions":[],"hashtags":[]},"retweet_count":0}

이를 파싱하려고 하는데... 자꾸 안되네요.. 이하는 제 코드입니다.

tweets_data = []
tweets_file = open(tweets_data_path, "r")
for line in tweets_file:
    try:
        tweet = json.loads(line)
        tweets_data.append(tweet)
    except:
        continue

자꾸 빈데이터가 되는데.. 이유가 무엇일련지요?

  • (•́ ✖ •̀)
    알 수 없는 사용자

2 답변

  • <a href="http://twitter.com/" rel="nofollow">Twitter for iPhone</a>
    

    때문에 shell 에서 테스트를 하면 디코딩 오류가 납니다.

    파일로 저장을 하고 아래와 같이 해보시기 바랍니다.

    import json
    with open('.savedJSONFile.json, encoding='UTF8') as f:
        jsonObj = json.loads(f.read())
        print(jsonObj['source'])
    
  • 올려주신 데이터가 JSON형식에 맞지 않아서 json.decoder.JSONDecodeError가 발생하는것 같아요.

    try-except문에서 except에 걸리기 때문에 append가 발생하지 않을것 같습니다. 올려주신 데이터에서 20110312000116101|를 제거한 문자열을 json parse해 봤더니 JSONDecodeError가 발생하네요.

    • 저도 마찬가지였는데, 앞의 숫자(아마 날짜 형식인 것 같습니다)를 |기준으로 split하여 제거하고 넣어봤는데 안되더라구요. 그래서 일단 예외처리로 넘겨버렸습니다. 알 수 없는 사용자 2017.3.7 11:58
    • 대체 왜 발생하는지 모르겠는데, 정확하게는 |로 나누게 되면 그 이후로부터 read가 꼬이더라구요. 갑자기 readline으로 읽었는데 갑자기 \n이 읽히질 않나, 이도 제거하였더니 이제는 " '' "가 잡히질 않나... 알 수 없는 사용자 2017.3.7 12:17
    • 뭐 여튼 그런걸 다 해결하더라도 ValueError: Expecting value: line 1 column 1 (char 0) 와 같은 에러가 발생하네요... 근데 신기하게도 readline이아니라 텍스트 그대로 긁어와 str으로 처리하면 에러가 발생하지 않는다는 겁니다... 알 수 없는 사용자 2017.3.7 13:37

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)