2015-06-07 5 views
1

Я пытался разобрать json-файл и выбрать некоторый атрибут.Python parsing json data

вот мой код

import json 
import urllib 

results = json.load(urllib.urlopen("https://www.kimonolabs.com/api/adgmajn2?apikey=L63EvSC1x5vG8iSbm9Jon3784mkDp1Or")) 

parse_result = json.loads(results) 
print parse_result 

А вот JSon формат данных

{ 
    "name": "google_test", 
    "count": 20, 
    "frequency": "Manual Crawl", 
    "version": 1, 
    "newdata": true, 
    "lastrunstatus": "success", 
    "thisversionstatus": "success", 
    "thisversionrun": "Sun Jun 07 2015 17:19:33 GMT+0000 (UTC)", 
    "results": { 
    "collection1": [ 
     { 
     "content": "Parse handles everything you need to store data securely and efficiently in the cloud. Store basic data types, including locations and photos, and query across ...", 
     "title": { 
      "href": "https://parse.com/products/core", 
      "text": "Parse Core | Everything your app needs to save data, be ..." 
     }, 
     "index": 1, 
     "url": "https://www.google.com.tw/webhp?sourceid=chrome-instant&ion=1&espv=2&es_th=1&ie=UTF-8#/es_th=1&q=pase%20data" 
     }, 
     { 
     "content": "Parsing or syntactic analysis is the process of analysing a string of symbols, either ... In order to parse natural language data, researchers must first agree on the ...", 
     "title": { 
      "href": "http://en.wikipedia.org/wiki/Parsing", 
      "text": "Parsing - Wikipedia, the free encyclopedia" 
     }, 
     "index": 2, 
     "url": "https://www.google.com.tw/webhp?sourceid=chrome-instant&ion=1&espv=2&es_th=1&ie=UTF-8#/es_th=1&q=pase%20data" 
     }, 
     { 
     "content": "In a data flow, Integration Services sources do the work of extracting data, parsing string data, and converting data to an Integration Services data type.", 
     "title": { 
      "href": "https://msdn.microsoft.com/en-us/ms141022.aspx", 
      "text": "Parsing Data - MSDN - Microsoft" 
     } 

     ...... 
    ] 
    } 

Однако, это показать мне некоторые ошибки. Я не понимаю, что это.

Traceback (most recent call last): File "get_json_data_2.py", line 6, in parse_result = json.loads(results) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/init.py", line 338, in loads return _default_decoder.decode(s) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 365, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) TypeError: expected string or buffer

+0

если ваша ссылка верна, тогда json.load ("") должен вернуть python dict, и вы можете проанализировать его с помощью значений ключа. –

+0

да! спасибо, я понял. –

ответ

7

results уже содержит разобранное дерево JSON. Вам не нужно loads часть:

import json 
import urllib 

results = json.load(urllib.urlopen("https://www.kimonolabs.com/api/adgmajn2?apikey=L63EvSC1x5vG8iSbm9Jon3784mkDp1Or")) 

print results 
+0

Спасибо, ты очень помог! Я понял. –

-3

Вы можете преобразовать JSON в YAML, используя, например, так: http://jsontoyaml.com/. Yaml - это «версия» json для python.

import yaml 

stram = open("test", "r") 
print yaml.load(stram) 
+1

Что делает черт: «Ямл - версия json для python». имею в виду? Это чепуха. –

+0

um, но зачем мне конвертировать в 'yaml'? Не работает ли обычный тип 'json' в python? На самом деле, мне нужно передать файл 'json' из другого скрипта. Итак, я боюсь ошибки типа. –

+0

@CodaChang JSON-парсинг работает отлично. –