Python-Json Parser - python

I am trying to implement python Json parser with the following set of rules:
Rule 1:
A JSON data object always begins with curly braces and ends with curly braces.
{}
Rule 2:
All data is represented in the form of
"string":value
where the value can be any of the following:
number
string
boolean
another json
Rule 3:
The rules for forming the strings (on the left hand side in red) are similar to rules for variables in most programming languages.
* They can be alphanumeric, but should always begin with a letter.
* They are case sensitive
* They can not contain special characters except underscores.
I worked on it and completed all the conditions except "another json". Hee is my code
import re
import string
class parser(object):
fp=open('jsondata.txt','r')
str=fp.read()
def __init__(self):
print "Name of the file Opened is :",self.fp.name
print "Contents of the file :\n",self.str
def rule1(self,str):
if self.str[:1].startswith('{'):
if self.str[:-1].endswith('}'):
print "RULE 1\n",
print "first character is '{' last character is '} : passed rule1\n"
else:
print "Not a JSON data"
def splitdata(self):
self.str=self.str[1:]
self.str=self.str[:-2]
print self.str
#Storing the words of string in a list
self.list1=[]
self.list1=re.split(',',self.str)
self.list2=[]
self.list3=[]
for i in self.list1:
self.list2=list(re.split(':',i))
self.list3.extend(list(self.list2))
self.left_list=[]
self.right_list=[]
self.i=0
self.left_list=list([self.list3[i] for i in range(len(self.list3)) if i % 2 == 0])
self.right_list=list([self.list3[i] for i in range(len(self.list3)) if i % 2 == 1])
print "DATA SPLIT"
print "Left elements of the json data:",self.left_list
print "Right elements of the json data:",self.right_list,"\n"
def left_parse(self):
"""we gona check "This part of the string":"This part will be checked in next function"\
Conditions imposed on left part of string:\
1.starts and ends with ""\
2.Starts with Alphabet\
3.Contains No special characters except unserscore _"""
for i in range(len(self.left_list)):
self.str1=self.left_list[i]
if self.str1.startswith('"') and self.str1.endswith('"')\
and self.str1[1].isalpha():
self.str2=self.str1[1:]
self.str3=self.str2[:-1]
print "Left side content:",self.str3
print "Status : Valid"if re.match("^[a-zA-Z0-9_]*$", self.str3) else "Invalid"
else:
print "Left side content:",self.str1
print "Status: Invalid"
obj=parser()
obj.rule1(str)
obj.splitdata()
obj.left_parse()
Now the problem is When i tried to check my right_list, whenever i get Another json data then the output goes wild. Can anyone please help me. i framed left_list and right_list based on splitting(comma and colon).
While parsing json inside a json this logic seems not working...

Related

simple print statement is not working inside method with if statement in python

I started learning Python code recently and one simple print statement is giving me trouble since last 4 days.
Problem: the print statement is not working inside the validatePostcode(postcode) method for if-statement. The assigned value is 200 (status code) which is printing fine without the if-statement. Also, when I compare with the True (result value) for that API it works fine without if-statement, why it is not working after I apply the if and try to compare?
Error:
File "./py_script3.py", line 32
print ("Congrats")
^
IndentationError: expected an indented block
#!/usr/bin/env python3
import os,re,sys
import urllib.request as req
import json
def loadJsonResponse(url):
#return json.loads(req.urlopen(url).read().decode('utf-8'))['result']
#return json.loads(req.urlopen(url).read().decode('utf-8'))['status']
print ("I am in loadJsonResponse before returning string")
string = json.loads(req.urlopen(url).read().decode('utf-8'))
return string
print ("I am in loadJsonResponse after returning string")
def lookuppostcode(postcode):
url = 'https://api.postcodes.io/postcodes/{}'.format(postcode)
return loadJsonResponse(url)
def validatePostcode(postcode):
url = 'https://api.postcodes.io/postcodes/{}/validate'.format(postcode)
#return loadJsonResponse(url)
string = json.loads(req.urlopen(url).read().decode('utf-8'))
Value = str(string['status'])
print (Value)
if Value == 200 :
print ("Congrats")
def randomPostcode():
url = 'https://api.postcodes.io/random/postcodes'
return loadJsonResponse(url)
def queryPostcode(postcode):
url = 'https://api.postcodes.io/postcodes?q={}'.format(postcode)
return loadJsonResponse(url)
def getAutoCompletePostcode(postcode):
url = 'https://api.postcodes.io/postcodes/{}/autocomplete'.format(postcode)
return loadJsonResponse(url)
#Input = input("Enter the postcode : ")
#print(lookuppostcode('CB3 0FA'))
validatePostcode('CB3 0FA')
#print(queryPostcode('HU88BT'))
#print(randomPostcode(Input))
This piece of code (which is generating the error):
if Value == 200 :
print ("Congrats")
Should be
if Value == 200 :
print ("Congrats")
Because python expects an indented block after the conditional, just like the message error is saying to you
You should indent the print statement like so:
if Value == 200 :
print ("Congrats")
You can read more about this here!
From https://docs.python.org/2.0/ref/indentation.html:
Leading whitespace (spaces and tabs) at the beginning of a logical line is used to compute the indentation level of the line, which in turn is used to determine the grouping of statements.
By doing
if Value == 200:
print ("Congrats")
Python interprets the two lines as two different groups of statements. What you should do is:
if Value == 200:
print ("Congrats")
Need to add an indent after the if statement. You can do so by pressing return after typing the colon
After the if-statement, a section of code to run when the condition is True is included. The section of must be indented and every line in this section of code must be indented the same number of spaces. By convention, four space indentation is used in Python.
if Value == 200:
print ("Congrats")

Python - True part of if condition always executes

No matter what's the value of what, the true part of if condition is always executed.
what = ""
def sendPacket(where, what):
print("sendPacket()> i/p what :" + what)
if what:
zb.send('tx',dest_addr_long = where,dest_addr = UNKNOWN,data = what)
print('sendPacket()> Data: '+ what)
print('sendPacket()> Data sent to: '+ where )
else:
print('sendPacket()> data not sent')
I want the true part to be executed only when what is not equal to null or empty.
Any help would be appreciated.
Ask explicitly for the condition you want:
if what and not what.isspace():
The above states that what is not null, is not an empty string, and is not a string of just whitespaces. It's possible that your input has some line break, tab, or other non-printable character that's messing with the test.

Python for loop scope

I'm trying to format a dictionary variable to use as a report. I want to recurse through the dictionary and concatenate the items from the dictionary into a formatted string that will be printed/emailed out to users. I'm having issues getting with the string variable (text) losing some of the text concatenated to it.
What I want is:
first \n
\t status: first did not have any updates to apply \n
second \n
\t status: first did not have any updates to apply \n
My function is:
def formatReport(report, text = ""):
for x in report:
if isinstance(report[x], dict):
text += "{0} \n".format(x)
formatReport(report[x], text)
else:
text += "\t{0}: {1} \n".format(x, report[x])
return text
When I call:
report = {'first': {'status': 'first did not have any updates to apply'}, 'second': {'status': 'second did not have any updates to apply'}}
formatReport(report)
I get (note the order of the output is not important to me):
'second \nfirst \n'
After adding a ton of debugging:
def formatReport(report, text = ""):
for x in report:
print "before if: " + text
if isinstance(report[x], dict):
text += "{0} \n".format(x)
print "if: " + text
formatReport(report[x], text)
else:
text += "\t{0} : {1} \n".format(x, report[x])
print "else: " + text
return text
I have narrowed the issue to down to the fact that the text variable is losing the string appended after the else. ie on this line:
text += "\t{0} : {1} \n".format(x, report[x])
So the output of the debugging code after the else is run the first time in the first for loop looks like:
else: second
status : first did not have any updates to apply
When it loops back to the top of the for loop is looks like:
before if: second
From what I have read for loops and if/else statements do not have their own scope as Python does not have block level scoping. I'm at a lose here I have tried all kinds of different combinations or variable names, parameters, etc.... It's worth noting I want to run this code on dictionaries that are 3+ levels deep, hence the need for the recursive call in the if statement.

Codeeval Challenge not returning correct output. (Python)

So I started doing the challenges in codeeval and i'm stuck at an easy challenge called "word to digit"
This is the challenge description:
Having a string representation of a set of numbers you need to print
this numbers.
All numbers are separated by semicolon. There are up to 20 numbers in one line. The numbers are "zero" to "nine"
input sample:
zero;two;five;seven;eight;four
three;seven;eight;nine;two
output sample:
025784
37892
I have tested my code and it works, but in codeeval the output is always missing the last number from each line of words in the input file.
This is my code:
import sys
def WordConverter(x):
test=str()
if (x=="zero"):
test="0"
elif (x=="one"):
test="1"
elif (x=="two"):
test="2"
elif (x=="three"):
test="3"
elif (x=="four"):
test="4"
elif (x=="five"):
test="5"
elif (x=="six"):
test="6"
elif (x=="seven"):
test="7"
elif (x=="eight"):
test="8"
elif (x=="nine"):
test="9"
return (test)
t=str()
string=str()
test_cases=open(sys.argv[1],'r')
for line in test_cases:
string=line.split(";")
for i in range(0,len(string)):
t+=WordConverter(string[i])
print (t)
t=str()
Am I doing something wrong? Or is it a Codeeval bug?
You just need to remove the newline char from the input. Replace:
string=line.split(";")
With
string=line.strip().split(";")
However, using string as the variable name is not a good decision...
When iterating over the lines of a file with for line in test_cases:, each value of line will include the newline at the end of the line (if any). This results in the last element of string having a newline at the end, and so this value won't compare equal to anything in WordConverter, causing an empty string to be returned. You need to remove the newline from the string at some point.

How to convert ASCII characterers to Strings in Python

I am trying to compare an ASCII character that I am receiving from the serial port with a string. I am not able to do that, even though it seems like I have converted the inputs successfully.
Here is my code
import serial
import time
port="/dev/ttyUSB0"
serialArduino= serial.Serial(port,9600)
serialArduino.flushInput()
inputs=""
while True:
inputsp=serialArduion.readline()
for letter in inputsp:
inputs=inputs+ str(letter)
print inputs
if inputs=="DOWN":
print "APPLES"
elif inputs=="UP"
print "Bannana"
ok so even though the input sometimes equals UP OR DOWN it still does not print out APPLES or Bannana
The return value of readline() contains newline. You need to strip newline.
import serial
import time
port="/dev/ttyUSB0"
serialArduino= serial.Serial(port,9600)
serialArduino.flushInput()
while True:
inputs = serialArduion.readline().rstrip()
if inputs == "DOWN":
print "APPLES"
elif inputs == "UP"
print "Bannana"
try this:
while True:
inputsp=serialArduion.readline()
for letter in inputsp:
inputs=inputs+ chr(letter)
print inputs
if inputs.lower() =="down":
print "APPLES"
elif inputs.lower() =="up":
print "Bannana"
Just changed 'str' to 'chr', which converts ASCII to a character. Other than this modification, strip off any other characters coming from input stream.

Categories