Python code examples

JSON PARSING EXAMPLE-1:

import json

# some JSON:

x = ‘{  “name”: “John”, “devlist”: [ {“name”:”kiny”, “age”:30,”city”:”New York”}]}’

# parse x:

y = json.loads(x)

# the result is a Python dictionary:

print(y[“name”])

print(y[“devlist”][0][“name”])

———————–RESULT—————————–

john

kiny

JSON PARSING EXAMPLE-2:

import json

# some JSON:

loradevice    = \

‘[{“devtype”:”dlab”,”deviceeui”: [“eui1”, “eui2”]}, \

  {“devtype”:”adenu”,”deviceeui”: [“eui3”, “eui4”]}]’

# parse x:

y = json.loads(loradevice)

# the result is a Python dictionary:

print(y[0][“devtype”])

print(y[0][“deviceeui”][0])

print(y[1][“devtype”])

print(y[1][“deviceeui”][1])

——————————RESULT————————

dlab

eui1

adenu

eui4

MISCELLANEOUS:

sys.path[0] = gives the directory where the python script was run from

path = “/home”  

# Join various path components  

print(os.path.join(path, “User/Desktop”, “file.txt”)) 

/home\User/Desktop\file.txt

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.