Tuesday, October 17, 2017

Curl python Requests




1) Convert Python Dictionary to Json string format


import json

python_data = {'ticket': {'comment': {'body': 'The smoke is very colorful.'}}}
json_string = json.dumps(python_data)
print(type(json_string))
print(json_string)



Pretty printing the JSON

You can also use json.dumps() to pretty print the JSON. Simply add an argument named indent to the json.dumps() method, as follows:

json_string = json.dumps(python_data, indent=2)

Output:

<type 'str'>
{
  "ticket": {
    "comment": {
      "body": "The smoke is very colorful."
    }
  }
}

==========================================

2) Convert Json String to Python Dictionary

import json
  
json_string = '{"article":{"title":"Great Expectations"}}'
python_data = json.loads(json_string)
print(type(python_data))
#print(python_data['article']['title'])


for i,j in python_data.items():
    print "%s => %s"%(i,j)

Output:
article => {u'title': u'Great Expectations'}

==========================================

3) Convert a Json file to a python dictionary

import json
with open('json.txt', mode='r') as f:
    python_data = json.load(f)
print(type(python_data))

print python_data


==========================================

4) Write python dictionary to a file in json format


python_data = {'ticket': {'comment': {'body': 'The smoke is very colorful.'}}}
json_string = json.dumps(python_data)
with open('json.txt', mode='w', encoding='utf-8') as f:
    f.write(json_string)

=============================================
5) To avoid print unicode character u ''
import pprint

app_details = u'hello'

def no_unicode(object, context, maxlevels, level):
    """ change unicode u'foo' to string 'foo' when pretty printing"""
    if pprint._type(object) is unicode:
        object = str(object)
    return pprint._safe_repr(object, context, maxlevels, level)

mypprint = pprint.PrettyPrinter()
mypprint.format = no_unicode
mypprint.pprint(app_details)





No comments:

Post a Comment