exception in input in python - exception

When running the following code:
try:
key=int(input())
except ValueError as string:
print("Error is within:",string)
for example, if one puts 'rrr' this exception will rise, since 'rrr' does not support (int)
However, instead ot putting the actual string, it puts: "invalid literal for int() with base 10: 'rrr' "
How do I make it work so that the variable 'string' actually gets the wrong input that the user gave (in this example, I want it to print: 'Error is within: rrr')
Thanks a lot

Store the input and convert it to an int separately.
key_str = input()
try:
key = int(key_str)
except ValueError:
print("Error is within:", key_str)

Your issue comes from the fact that the variable string is the error message for a ValueError exception. If you wanted to print out the user's invalid input, you would need to create a variable that stores the user's input before your try/except. For example:
userInput = input()
try:
key=int(userInput)
except ValueError:
print("Error is within:",userInput)

You can just parse the error msg :D
print("Error is within:", string.args[0][41:-1])

Related

Unable to unmarshal json into protobuf message

My problem is pretty much the opposite of this one: Unable to unmarshal json to protobuf struct field
I have a message with several nested messages of the following form:
message MyMsg {
uint32 id = 1;
message Attribute {
...
}
repeated Attribute attrs = 2;
message OtherAttribute {
...
}
OtherAttribute oAttr = 3;
...
}
Some external dependencies will send this message JSON form, which needs to then be unmarshalled into a go struct. When trying to use jsonpb like so, where resp is a *http.Response:
msg := &MyMsg{}
jsonpb.Unmarshal(resp.Body, msg)
The message is not fully decoded into the struct, i.e. some of the nested structs are missing. When the message is however decoded simply using encoding/json like so:
msg := &MyMsg{}
json.NewDecoder(resp.Body).Decode(msg)
All attributes are successfully decoded into the struct.
As jsonpb is the official package to (un)marshall between protobuf/json, I was wondering whether anyone has any idea as to why this type of behaviour could occur. Do the default behaviours for jsonpb and encoding/json differ in a way that would explain one being able to unmarshall and the other not? If so where would one configure the behaviour of jsonpb accordingly?
The default behaviour of encoding/json is the following:
Unknown fields are allowed, i.e. in case of a field not matching it is simply ignored without an error being raised.
Before it is ignored, the Decoder attempts to match the field without case sensitivity
The behaviour in point 1 can be replicated in jsonpb by using the Unmarshaller struct and setting the property AllowUnknownFields to true
var umrsh = jsonpb.Unmarshaler{}
umrsh.AllowUnknownFields = true
msg := &MyMsg{}
umrsh.Unmarshal(resp.Body, msg)
It does not seem to be possible to replicate the behaviour from point 2 within jsonpb.

Trying to get a simple loop of JSON passed to POST - Python

I have a WS using Flask/python 2.7. I have 1 JSON object passed to the WS. I have been successful in capturing the object and returning the whole JSON.
I have looked all over for examples (many use print of test dataset in python) and have tried json.dumps, json.loads, json.dump, json.load, for loops, etc.
What I would like to do seems simple and I know it is me, but I get errors no matter what I try. I am trying to parse the JSON, put the values in to variables, and do "stuff".
This works:
#app.route('/v1/test', methods = ['POST'])
def api_message():
if request.headers['Content-Type'] == 'application/json':
return "JSON Message: " + json.dumps(request.json, separators=(',',':'))
else:
return "415 Unsupported Media Type"
This does not (and many variations of this using different things):
jsonobject = json.dumps(request.json)
pstring = json.loads(jsonobject)
for key, value in pstring.iteritems():
return value
What I want to do (pseudo code):
for each JSON
get the name value pairs in to a place where I can do something like this (which was done on a flat file)
input_data = pd.read_csv(sio, delimiter=',', names=columns)
probs = model.predict_proba(input_data)
I am sure I didn't make this as clear as I could but it is a challenge because I get errors like below (examples -- not all at once of course) with all the different things I try:
AttributeError: 'dict' object has no attribute 'translate'
TypeError: 'dict' object is not callable
AttributeError: 'str' object has no attribute 'iteritems'
So after all that, what is the right way to do this?

Getting line number of json file at which the json validation failed

I am using json-schema-validator for validating my json.
I want to show the line number in the json data file where the validation failure occurs. I want to show the failure messages in the user friendly manner.
I get the pointer to the json node where the validation failure might have occurred as follows:
JsonNode jsondatanode = JsonLoader.fromFile(new File("jsondata.json"));
JsonNode jsonschemanode = JsonLoader.fromFile(new File("jsonschema.json"));
final JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
final JsonSchema datastoreschema = factory.getJsonSchema(jsonschemanode);
ProcessingReport report;
report = datastoreschema.validate(jsondatanode);
However the pointer is inconvenient to locate the json object/attribute when the json file contains many nodes of type specified by the pointer.
I got following validation failure message:
--- BEGIN MESSAGES ---
error: instance value (12) not found in enum (possible values:["true","false","y","n","yes","no",0,1])
level: "error"
schema: {"loadingURI":"#","pointer":"/properties/configuration/items/properties/skipHeader"}
instance: {"pointer":"/configuration/0/skipHeader"}
domain: "validation"
keyword: "enum"
value: 12
enum: ["true","false","y","n","yes","no",0,1]
--- END MESSAGES ---
I want to show the custom message for validation failures with the line number in json data file which caused schema validation failure. I know I can access the individual details of validation report as shown in below code.
I want to show the custom message as follows:
List<ProcessingMessage> messages = Lists.newArrayList((AbstractProcessingReport)report);
JsonNode reportJson = messages.get(0).asJson();
if(reportJson.get("keyword").toString().equals("enum"))
{
System.out.println("Value "+report.Json.get("value").toString() +"is invalid in " + filepath + " at line " + linenumber);
}
else if{
//...
}
//...
What I dont understand is how can I get that linenumber variable in above code.
Edit
Now I realize that
instance: {"pointer":"/configuration/0/skipHeader"}
shows which occurrence of skipHeader is into problem and in this case its 0th instance of skipHeader inside configuration. However I still think its better to get the line number which ran into problem.
(library author here)
While it can be done (I have somewhere an implementation of JsonParser which does just that) the problem is that the line/column information will most of the time be irrelevant.
In order to save bandwidth, most of the time, JSON sent over the wire will always be on a single line, therefore the problem will remain that you would get, say, "line 1, column 202" without getting any the smarter.
I'll probably do this anyway for the next major version but for 2.2.x it is too late...

Unexpected escape character error in SparkSql

I am trying to read the json file through the code
val i = sqlContext.jsonFile("file_name.json") using scala
.It gives me error "unexpected escape character: a".
When i enclose this line within try catch, even then it gives the same error.
try{
val i = sqlContext.jsonFile("File_name.json")
}catch{
case ex: Exception=>println("error")
}
Why is this happening? Anybody has any idea? How can i read my json file?
I am trying to learn SparkSql.

JSON.parse Map want String get integer

Dart is great, it's like, well, programming. Also the IDE is great.
I have encountered what appears to me to be a problem (for me) with the Dart
JSON.parse function. The problem appears to me to be that if a string
is an integer, it creates an integer in the Map. This may not be desirable
because there could be situations where string fields contain numeric.
eg. an address that contains just the street number. Or, perhaps I am
simply doing something wrong.
The line of code that exposes the possible problem is :
String sId = mAcctData['I_Id'];
I presume that there is a logical solution to this, and if so I would
appreciate being advised
httpSubmitAccountNrLoadEnd(HttpRequest httpReq) {
String sResponse = null;
if (httpReq.status != 200) {
print('On Http Submit Account Nr. There was an error : status = ${httpReq.status}');
} else {
print("On Return from Http Submit Account Nr. no error - status = ${httpReq.status}");
sResponse = httpReq.responseText;
}
print("Response From Submit Account Nr. = ${sResponse}"); // print the received raw JSON text
Map mAcctData = JSON.parse(sResponse);
print ("Json data parsed to map");
print ("Map 'S_Custname' = ${mAcctData['S_Custname']}");
String sCustName = mAcctData['S_Custname'];
print ("About to extract sId from Map data");
String sId = mAcctData['I_Id'];
print ("sId has been extracted from Map data");
String sAcctNr = mAcctData['I_AcctNr'];
String sAcctBal = mAcctData['I_AcctBal'];
The following is the console output.
The line that shows the problem that I have is:
Exception: type 'int' is not a subtype of type 'String' of 'sId'.
About to send http message
On Return from Http Submit Account Nr. no error - status = 200
Response From Submit Account Nr. = {"S_Custname":"James Bond","I_Id":1,"I_Acctnr":123456789,"I_AcctBal":63727272,"I_AvailBal":0}
Json data parsed to map
Map 'S_Custname' = James Bond
About to extract sId from Map data
Exception: type 'int' is not a subtype of type 'String' of 'sId'.
Stack Trace: #0 httpSubmitAccountNrLoadEnd (http://127.0.0.1:3030/C:/Users/Brian/dart/transact01/transact01.dart:75:31)
1 submitAccountNr.submitAccountNr. (http://127.0.0.1:3030/C:/Users/Brian/dart/transact01/transact01.dart:33:59)
Exception: type 'int' is not a subtype of type 'String' of 'sId'.
Stack Trace: #0 httpSubmitAccountNrLoadEnd (http://127.0.0.1:3030/C:/Users/Brian/dart/transact01/transact01.dart:75:31)
1 submitAccountNr.submitAccountNr. (http://127.0.0.1:3030/C:/Users/Brian/dart/transact01/transact01.dart:33:59)
Questions:
Is there a solution to this? (eg. force JSON.parse to create strings)
Is there a better way to handle this? (eg. extract data directly from the JSON string)
From what I see in your sResponse mAcctData['I_Id'] is really an int :
{
"S_Custname": "James Bond",
"I_Id": 1,
"I_Acctnr": 123456789,
"I_AcctBal": 63727272,
"I_AvailBal": 0
}
So if you want to get a String for mAcctData['I_Id'] you can use int.toString() :
String sId = mAcctData['I_Id'].toString();
Just turn your integers into strings if you want them to be like that:
{
"S_Custname": "James Bond",
"I_Id": "1",
"I_Acctnr": "123456789",
"I_AcctBal": "63727272",
"I_AvailBal": "0"
}
Now it should work fine. Alternatively, use .toString() to convert the integers into strings.