Python-如何解析JSON字符串 [英] Python - How to parse JSON string

查看:592
本文介绍了Python-如何解析JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一种解析JSON字符串并将其保存到mysql中的方法. 这是我的json!

I am trying to find a way to parse a JSON string and save them into mysql. This is my json!

{"title": My title, "desc": mydesc, "url": http//example.com}

从现在开始,我没有问题使用json.dumps()将所有json保存到一列,所以实际上我正在尝试解析每个joson数据字符串以将其发送到mysql表.标题| Desc |网址.

From now i don't have problem to save all json into one column usining json.dumps() so actually I'm trying to parse each joson data string to send him to mysql table. Title | Desc | Url.

这是我的desc示例的python代码(pyspider-resultdb.py)

This is my python code for desc example (pyspider-resultdb.py)

def _parse(self, data):
    for key, value in list(six.iteritems(data)):
        if isinstance(value, (bytearray, six.binary_type)):
            data[key] = utils.text(value)
    if 'result' in data:
        decoded = json.loads(data['result'])
        data['result'] = json.dumps(decoded['desc'])
    return data

def _stringify(self, data):
    if 'result' in data:
         decoded = json.loads(data['result'])
         data['result'] = json.dumps(decoded['desc'])
    return data

推荐答案

目前尚不清楚您要实现的目标,但是如果您的问题是如何将JSON转换为python dict然后加载到表中,那么方法就是这样你可以做到的:

It's unclear from your question what you trying to achieve, but If your question is how to convert JSON to python dict and then load to the table, then that's how you can do it:

my_dict = json.loads('{"title": "foo", "dest": "bar"}')
curs.execute('INSERT INTO test (title, dest) values(%(title)s, %(dest)s)', my_dict)

这篇关于Python-如何解析JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆