How to read field from JSON encoding of XML message - python

Is there a way I can get the errorMessage tag from this response using some code in python?
{
"movies_search":{
"#xmlns":"http://www.ourmoviest.com/mv",
"#xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance",
"#xsi:schemaLocation":"http://www.ourmoviest.com/mv mv.xsd ",
"error":{
"errorMessage":"We cannot proceed search",
"statusCode":"00004"
}
}
}

The following Python script,
import json
respStr = """
{
"movies_search":{
"#xmlns":"http://www.ourmoviest.com/mv",
"#xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance",
"#xsi:schemaLocation":"http://www.ourmoviest.com/mv mv.xsd ",
"error":{
"errorMessage":"We cannot proceed search",
"statusCode":"00004"
}
}
}
"""
respObj = json.loads(respStr)
print respObj['movies_search']['error']['errorMessage']
will print the errorMessage string,
We cannot proceed search
as requested.

Yes, there is. See https://docs.python.org/2/library/json.html "Decoding JSON".
(I'm really tempted to simply ask "what have you tried yourself to reach the goal"...)
Edit: as requested by the first comment, here the essential code instead of a link-only answer:
import json;
responseJson = json.loads(response)
responseJson['movies_search']['error']['errorMessage']

Related

using symbols in json in python

Recently, I got a problem while working with json in python. Actually that is about special symbols in json. The problem is defined with code below:
import json
app = {
"text": "°"
}
print(json.dumps(app, indent=2))
but giving this I get this:
{
"text": "\u00b0"
}
Here the ° sign is replaced with \u00b0. But I want it to be exact as my input. How can I do it?
Thanks in advance.
According to https://pynative.com/python-json-encode-unicode-and-non-ascii-characters-as-is/, you want to set ensure_ascii=False:
>>> import json
>>> app={"text": "°"}
>>> print(json.dumps(app, indent=2, ensure_ascii=False))
{
"text": "°"
}

Python: Pretty print json file with array ID's

I would like to pretty print a json file where i can see the array ID's. Im working on a Cisco Nexus Switch with NX-OS that runs Python (2.7.11). Looking at following code:
cmd = 'show interface Eth1/1 counters'
out = json.loads(clid(cmd))
print (json.dumps(out, sort_keys=True, indent=4))
This gives me:
{
"TABLE_rx_counters": {
"ROW_rx_counters": [
{
"eth_inbytes": "442370508663",
"eth_inucast": "76618907",
"interface_rx": "Ethernet1/1"
},
{
"eth_inbcast": "4269",
"eth_inmcast": "49144",
"interface_rx": "Ethernet1/1"
}
]
},
"TABLE_tx_counters": {
"ROW_tx_counters": [
{
"eth_outbytes": "217868085254",
"eth_outucast": "66635610",
"interface_tx": "Ethernet1/1"
},
{
"eth_outbcast": "1137",
"eth_outmcast": "557815",
"interface_tx": "Ethernet1/1"
}
]
}
}
But i need to access the field by:
rxuc = int(out['TABLE_rx_counters']['ROW_rx_counters'][0]['eth_inucast'])
rxmc = int(out['TABLE_rx_counters']['ROW_rx_counters'][1]['eth_inmcast'])
rxbc = int(out['TABLE_rx_counters']['ROW_rx_counters'][1]['eth_inbcast'])
txuc = int(out['TABLE_tx_counters']['ROW_tx_counters'][0]['eth_outucast'])
txmc = int(out['TABLE_tx_counters']['ROW_tx_counters'][1]['eth_outmcast'])
txbc = int(out['TABLE_tx_counters']['ROW_tx_counters'][1]['eth_outbcast'])
So i need to know the array ID (in this example zeros and ones) to access the information for this interface. It seems pretty easy with only 2 arrays, but imagine 500. Right now, i always copy the json code to jsoneditoronline.org where i can see the ID's:
Is there an easy way to make the IDs visible within python itself?
You posted is valid JSON.
The image is from a tool that takes the data from JSON and displays it. You can display it in any way you want, but the contents in the file will need to be valid JSON.
If you do not need to load the JSON later, you can do with it whatever you like, but json.dumps() will give you JSON only.

How to handle JSON with Python?

I'm very new to Python. I have a JSON response like this :
{
"Code" : "Success",
"LastUpdated" : "2012-10-19T08:52:10Z",
}
I need to get the value of Code, which is Success. How can I do that in Python?
Search for json in the documentation . You'll find the json module explained, with examples.
import json
# ... you read here from the file
data = '''{
"Code" : "Success",
"LastUpdated" : "2012-10-19T08:52:10Z"
}'''
result = json.loads(data)
print result['Code']
Be careful with the format!! I removed the comma after "LastUpdated" : "2012-10-19T08:52:10Z", because this is not a valid json.

check whether data is in json format or not in python

This is my test class and i am trying to unittest my method that is createaccount()
class CreateAccountTest1(unittest.TestCase):
def testCreateAccount_1(self,data):
text = "{'user_id':'abc123','action':'add','names':['hello','world']}"
regex = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(text.replace(/"(\\.| [^"\\])*"/ g, ''))) && eval('(' + text + ')')
self.assertRegexpMatches(text, reg, 'my msg')
createaccount() method is
class CreateAccountClass():
def CreateAccount(self,data):
Now i have to check whether the parameter of the createaccount() is in json format or not.
if i pass data=
{ "_id" : "user#gmail.com", "H_id" : "smsg0", "name" : "vish", "passwrd" : "xj45cd" }
it should check whether it is json or not,
and i am sure that this is in json format.
now in my method createaccount() it should check whether the data is in json format or not,
if not it should print error message, if it works with regex ? or any suggestions,
Thanks,
import json
try:
json.loads(data)
except ValueError:
print("data was not valid JSON")
Look at this answer. Also, I'd suggest not to perform this check with regexes, just do it with a standard parser and check for the errors using json.load

Python JSON encoder

I have a dict like this:
data = {"data":"http://abc/def"}
when I call json.dumps(data) I get this:
'{"data":"http://abc/def"}'
but I want this:
'{"data":"http:\/\/abc\/def"}'
because I use jquery to parse json but seems like it don't understand unescaped solidus, or is there any way to make jquery understand?
UPDATE
For example, here is my json data
{"data": ["http://abc.com/aaaaaaaa/bbbbbbbbb/cccccccccc/xyz.mp3"]}
Here is my success function
function showResult(result) {
$.each(result.data, function(i, item){
link = $('<a>').attr('href', item).text(item)
$("#result").append('<br>')
$("#result").append(link);
});
}
The result should be a hyperlink to
http://abc.com/aaaaaaaa/bbbbbbbbb/cccccccccc/xyz.mp3
But I got a hyperlink to
http://abc.com/aaaaaaaa/bbbbbbbbb/cccccccccc/xyz.mp3
If replace all '/' by '\/', everything is fine
Normally you don't escape forward slashes in JSON, but if you are certain this is your problem you can simply do this:
s = json.dumps(data)
s = s.replace("/", "\\/")

Categories

Resources