免责声明:我是解析和访问JSON的新手,我只是开始了解django的绳索。
详细信息:
我正在尝试访问我在django模板中获取的JSON对象中的一些数据:
示例JSON:
{"entry":[
{"id":"1234567","hash":"1234567",
..."name":{"givenName":"John","familyName":"Doel","formatted":"John H. Doe"},
..."currentLocation":"Los Angeles, CA",
..."emails":[{"primary":"true","value":"jdoe@example.com"}],
..."accounts":[
...{"domain":"facebook.com","url":"http:\/\/www.facebook.com\/john.doe",..."shortname":"facebook"},
...{"domain":"twitter.com","display":"@jdoe411","url":"http:\/\/twitter.com\/jdoe411",..."shortname":"twitter"}],
..."urls":[{"value":"http:\/\/www.example.com","title":"example url"},]}
]}
使用Django模板标签获取:
@register.inclusion_tag('includes/gravatar_links.html')
def gravatar_links(email, first_name):
url = "http://www.gravatar.com/" + hashlib.md5(email.lower()).hexdigest()
url += '.json'
response = urllib2.urlopen(url)
interm = simplejson.load(response)
data = simplejson.dumps(interm)
name = first_name
return {'gravatar_links': {'name': name, 'data': data}}
我只是调用{{ gravatar_links.name }}
和{{ gravatar_links.data }}
,我可以看到用户名和所描述的JSON数据。
目标:
我想访问JSON对象中的特定键,即"accounts"
和"urls"
,并自定义输出,(例如)"Follow {{ gravatar_links.name }} on <a href="{{ gravatar_links.data.accounts.url }}">{{ gravatar_links.data.accounts.shortname }}</a> and see their work at <a href="{{ gravatar_links.data.urls.url }}">{{ gravatar_links.data.urls.title }}</a>"
理想情况下会产生:
"Follow John on Twitter and Facebook and see their work at example url"
问题:
"accounts"
作为列表出现,我该如何将其输出为逗号分隔列表?答案 0 :(得分:0)
对于以逗号分隔的列表,您使用Django中的join
模板标记(https://docs.djangoproject.com/en/dev/ref/templates/builtins/):
{{ accounts|join:", " }}
如果你想要更加花哨,你可以编写自己的模板标签(并不像看起来那么困难!)。
答案 1 :(得分:0)
模板标签应该是:
@register.inclusion_tag('includes/gravatar_links.html')
def gravatar_links(email, first_name):
url = "http://www.gravatar.com/" + hashlib.md5(email.lower()).hexdigest()
url += '.json'
response = urllib2.urlopen(url)
interm = simplejson.load(response)
accounts_list = interm["entry"][0]["accounts"]
data = simplejson.dumps(interm)
return {'gravatar_links': {'accounts': accounts_list, 'name': first_name, 'data': data}}
然后要访问json对象的元素,我们可以继续使用类似accounts_list = interm["entry"][0]["accounts"]
的内容,除了"urls"
我们有urls_list = interm["entry"][0]["urls"]
对于具有多个dictionary
[element: {key1=>value1, ...}, {key2=>value2, ...}]
个and follow {{ gravatar_links.name }} on
{% for o in gravatar_links.accounts %}
{% if not forloop.first and not forloop.last %}, {% endif %}
{% if forloop.last %} and {% endif %}
<a href="{{ o.url }}">{{ o.shortname }}</a>
{% if forloop.last %}.{% endif %}
{% endfor %}
的元素,只需在模板中设置for循环并迭代这样的项目:
if forloop
额外的and follow John on facebook and twitter.
语句将构成我们的输出:
and follow John on facebook, linkedin, and twitter.
超过2个网址: {{1}}