简体   繁体   中英

How to handle the JSON formatted string?

I use json.dumps() to handle the value and want to display them in the front-end.

I set the header to "application/json",but it doesn't work well and the quote is converted to " in the browser.

How do I convert them to the normal output like {"key": "value"} rather than {"key": "value"} ?

This is my url .I use web.py to handle the data.

import json
import os
import urllib2
import web

app_root = os.path.dirname(__file__)
templates_root = os.path.join(app_root, 'templates')
render = web.template.render(templates_root)

class Callback:
    def GET(self):
        web.header('Content-Type', 'application/json; charset=utf-8')
        url = "http://www.reddit.com/r/pics/hot.json"
        hdr = { 'User-Agent' : 'super happy flair bot by /u/spladug' }
        req = urllib2.Request(url, headers=hdr)
        html = urllib2.urlopen(req).read()
        html = json.dumps(html)  
        func_name = web.input()['callback']
        html = '{0}({1})'.format(func_name, html)
        return render.callback(html)

Change return render.callback(html) to return html - no need for the template engine here.

Also, you might consider using the requests module instead of urllib2. It's much nicer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM