zl程序教程

您现在的位置是:首页 >  后端

当前栏目

python 中json和字符串互相转换

Python转换JSONJSON 字符串 互相
2023-09-11 14:22:10 时间

python 中json和字符串互相转换
string =" {
  "status": "error",
  "messages": ["Could not find resource or operation 'BZK1.MapServer' on the system."],
  "code": 404

}"

print  '对象:' string

print '取值:' json.loads(string)['code']

输出结果为:

对象:{u'status': u'error', u'code': 404, u'messages': [u"Could not find resource or operation 'BZK1.MapServer' on the system."]}

取值:404

将对象转成字符串:

resultJson = {"state": 1}
print( json.dumps(resultJson))
分别使用了Json包中的loads()方法和dumps()方法

ast的用法

import ast 

def get_dict_for_longtext(data):
    # [{"var_name":"key","var_remark":"e92354cdeefdd61d47dea5691d1e784b"}]
    a = data[1:len(data)-1]   #去除中括号
    # print(a)
    # print("type(a):",type(a))
    c = ast.literal_eval(a)
    my_dict={}
    for key,value in c.items():
        print(key)
        print(value)
        my_dict[key]=value
    return my_dict

import ast
#字符串转成字典
text = ast.literal_eval("{'google': 'google.com', 'runoob': 'runoob.com'}")
print(text)
print(type(text))
def string_to_dict(self,text):
    text = ast.literal_eval(text)
    print(text)
    return text
def my_run():

    data=[{"var_name":"gid","var_remark":"sh601009"},{"var_name":"key","var_remark":"e92354cdeefdd61d47dea5691d1e784b"}]
    s = '{"var_name":"content-type","var_remark":"application/json"}'
    d = ast.literal_eval(s)  #字符串转list
    print(type(d))
    print(d['var_name'])
    my_dict={}
    for key,value in d.items():
        print(key)
        print(value)
        my_dict[key]=value
    # d2=json.load(d)
    # print(type(d2))
    return my_dict
def my_run2():
    data='[{"var_name":"gid","var_remark":"sh601009"},{"var_name":"key","var_remark":"e92354cdeefdd61d47dea5691d1e784b"}]'
    d = ast.literal_eval(data)
    # print(type(d))
    # print(d[0])
    # print(type(d[0]))
    for a in d:
        for key,value in a.items():
            print(value)