Skip to content

Instantly share code, notes, and snippets.

@jiwanlimbu
Forked from JamesOBenson/json misc
Created September 6, 2017 15:21
Show Gist options
  • Save jiwanlimbu/2f02d558ed4d31550de801e19ea9d2b2 to your computer and use it in GitHub Desktop.
Save jiwanlimbu/2f02d558ed4d31550de801e19ea9d2b2 to your computer and use it in GitHub Desktop.
Random json examples.
## Python 2.7
>>> import json
>>> import sys
>>>
>>> #load the data into an element
... data={"test1" : "1", "test2" : "2", "test3" : "3"}
>>>
>>> #dumps the json object into an element
... json_str = json.dumps(data)
>>>
>>> #load the json to a string
>>> resp = json.loads(json_str)
>>>
>>> #print the resp
>>> print (resp)
{u'test1': u'1', u'test3': u'3', u'test2': u'2'}
>>>
>>> #extract an element in the response
... print (resp['test1'])
1
data.json:
{
"admin": [
{
"id": "ken",
"admin_unit": "0",
},
{
"id": "don",
"iscategorical": "0"
}
],
"masks": {
"id": "valore"
},
"om_points": "value",
"parameters": {
"id": "valore"
}
}
>>> import json
>>> from pprint import pprint
>>> with open('data.json') as data_file:
... data = json.load(data_file)
...
>>> # Print the data
>>> pprint(data)
{u'maps': [{u'id': u'blabla', u'iscategorical': u'0'},
{u'id': u'blabla', u'iscategorical': u'0'}],
u'masks': {u'id': u'valore'},
u'om_points': u'value',
u'parameters': {u'id': u'valore'}}
>>>
>>> # Print specific values from json set:
>>> data["maps"][0]["id"]
u'blabla1'
>>> data["masks"]["id"]
u'valore'
>>> data["om_points"]
u'value'
>>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment