I have an output :
result = {
"sip_domains":{
"prefix":[{"name":""}],
"domain":[{"name":"k200.com"},{"name":"Zinga.com"},{"name":"rambo.com"}]
},
"sip_security":{"level":2},
"sip_trusted_hosts":{"host":[]},
"sip_proxy_mode":{"handle_requests":1}
}
from this i just wanted the output to print to my screen :
domain : k200.com
domain : Zinga.com
domain : rambo.com
how can i get this output using regular expression
Help needed urgently
If it's the text you need to parse then Use JSON module to parse the JSON payload:
http://docs.python.org/library/json.html?highlight=json#json
Regular expression are not needed with good programming language like Python.
Otherwise if it's Python dictionary then use Python dictionary [] style item access to read data from the dictionary.
If you are getting this data as a string from somewhere you must convert it to a python dictionary object to access it. You should not have to use any regular expressions to get this output.
import json
# get the json str somehow
json_dict = json.loads(json_str)
for domain_dict in json_dict['sip_domains']['domain']:
print 'domain : %s' % (domain_dict['name'])
Related
I have a JSON output like this:
{
":output":{
"response":"{ \"ParentId\" : 125, \"ParentKey\" : { \"key\" : \"9aqews-uwdguwdw8-9uw8\", \"identity\" : \"key_ID=674\" } }"
}
}
I'm trying to fetch the content of key, that is: 9aqews-uwdguwdw8-9uw8
Here are somethings that tried:
------------------------------------------------------
${json_data} Parse Json ${output}
Log ${json_data["output"]["response"]}
Log ${json_data["output"]["response"][0][0:10]}
------------------------------------------------------
${json}= Convert To Dictionary ${values}
${j_keys}= Get Dictionary Keys ${json}
Log ${j_keys}
------------------------------------------------------
${values}= Evaluate json.loads($output) json
Log ${values['output']['response'][1]}
-----------------------------------------------------
${KeySP}= Get Substring ${values} "key" ","
Log ${keySP}
------------------------------------------------------
#${parkeydict}= ${values['output']['response']}
#${keyspacedict}= ${parkeydict['ParentKey']}
#Log ${keyspacedict['key']}
------------------------------------------------------
I have tried several other steps, possibilities and keywords,
The best I could parse is till "Log ${json_data["output"]["response"]}" which returns data from 'response'.
It fails even if I convert to Dict and access the 'key', I think that further data after 'response' is completely stored as values.
Can someone help/guide me on how to capture the data in 'key' variable?
Thanks in Advance!
The first problem is that you're trying to use ['output'], but the key is :output.
The second problem is that the value of the "response" key is not a dictionary, it's a string that looks like a dictionary. You must convert it to a dictionary before you try to pull values from it, assuming it is indeed an well-formed json dictionary and not just a string that might look like a dictionary.
This works for me on the exact data provided in the question:
${values}= Evaluate json.loads($output)
${response}= Evaluate json.loads($values[':output']['response'])
${key}= set variable ${response['ParentKey']['key']}
should be equal ${key} 9aqews-uwdguwdw8-9uw8
Note: if you're using a version of robot that is older than 3.2 you'll need to include json as a final argument for the Evaluate command so that robot knows to import the module. Starting with version 3.2 and onward, modules used in the expression are automatically imported.
I'm using an API that is giving me and output formatted as
['{"quote":{"symbol":"AAPL"', '"companyName":"Apple Inc."', '"primaryExchange":"Nasdaq Global Select"', '"sector":"Technology"', '"calculationPrice":"close"', '"open":367.88', '"openTime":1593696600532', '"close":364.11', '"closeTime":1593720000277', '"high":370.47', '"low":363.64', '"latestPrice":364.11'}]
...(it keeps going like this with many more categories.)
I am attempting to pull out only the latest price. What would be the best way to do that?
This is what I have but I get a bunch of errors.
string = (data.decode("utf-8"))
data_v = string.split(',')
for word in data_v[latestPrice]:
if word == ["latestPrice"]:
print(word)
print(data_v)
Judging by the output this is JSON. To parse this easily use the JSON module (see https://docs.python.org/3/library/json.html ).
If I'm correct you got this output from Yahoo Finance, if this indeed the case don't fetch and parse it manually but use the yfinance module (see https://pypi.org/project/yfinance/ )
You will have to use JSON module to parse this JSON string. You can convert it into dictionary then. I have indented the JSON code for ease of understanding. You can use the following approach,
import json
text_to_parse = """
{"quote":
{
"symbol":"AAPL",
"companyName":"Apple Inc.",
"primaryExchange":"Nasdaq Global Select",
"sector":"Technology",
"calculationPrice":"close",
"open":367.88,
"openTime":1593696600532,
"close":364.11,
"closeTime":1593720000277,
"high":370.47,
"low":363.64,
"latestPrice":364.11
}
}
"""
parsed_dict = json.loads(text_to_parse)
print(parsed_dict["quote"]["latestPrice"])
When the program is run, it outputs 364.11
I am trying to pass a JSON object as an argument to a python2 script, it works but the final json data has a single quote (') enclosing the object.
Below is my code
import json
import sys
print sys.argv[1]
data_str = sys.argv[1].decode('string-escape')
print data_str
# The above print's fine with no single quotes
json_data= {
"server-name": "servername",
"transaction-id": "transaction_id",
"user-id": "user_id",
"change-id": "change_id",
"consumer-name": "consumer_name",
"platform": "platform",
"cookbooks": [
{
"cookbook-name": "cookbook_name",
"cookbook-version": "cookbook_version",
"recipe-name": "receipie_name",
"attributes": {
}
}
]
}
json_data["cookbooks"][0]["attributes"] = data_str.decode('string-escape')
print json_data["cookbooks"]
Execution
C:\Python26\python.exe saver.py "{apple:newf,mango:newb}"
{apple:newf,mango:newb}
{apple:newf,mango:newb}
[{'cookbook-name': 'cookbook_name', 'cookbook-version': 'cookbook_version', 'recipe-name': 'receipie_name', 'attributes': '{apple:newf,mango:newb}'}]
From the above output the final json_data contains quotes in the attribute value
'attributes': '{apple:newf,mango:newb}' which is causing error in my GET call.
How to escape this single quote. ?
Forgive me if I'm wrong but I think you've got mixed up with converting the argument string type and decoding a json string.
The single quotes in your result means that the entire value is a string.
Firstly the argument you are passing in on the command line isn't valid JSON.
Try starting your program like this:
C:\Python26\python.exe saver.py "{\"apple\":\"newf\",\"mango\":\"newb\"}"
Then later decode the JSON contained in the string like this:
json_data["cookbooks"][0]["attributes"] = json.loads(data_str)
i.e. json.loads and not str.decode
at this point the variable "json_data" isn't holding JSON it's holding a dictionary
You would then have to encode the entire of json_data to pass it in some raw form of http GET unless you have some API doing it for you. Something like
encoded_json_data = json.dumps(json_data)
If you want to work with JSON then use the json module built in to your Python. Don't try to fudge the issue by treating it as Python string data when it isn't.
import json
then:
json_data["cookbooks"][0]["attributes"] = json.loads(sys.argv[1])
Then if you want to output your Python data structure as json:
print(json.dumps(json_data["cookbook"]))
I am trying to convert an xml file to JSON.
In the python script, I am reading the xml file, store the tags in a dict and then dump into JSON.
The issue is that some of the tag in xml file are optional. As of now i am handling it via IF-conditions. I wanted to check is there is a better way of handling this?
My dict object looks something like this.
In this for example, some entries in the XML may have the tab for Variables, and others may not.
dictData[dictFolder['FOLDER_NAME']][dictJob['JOBNAME']] = {
'Type' : dictJob['JOBTYPE'],
'Command' : dictJob['SCRIPTNAME'],
'Description' : dictJob['DESCRIPTION'],
'When' : {'WeekDays' : dictJob['SCHEDULE'],
'FromTime' : dictJob['FROMTIME']},
'Variables' : [varDict],
'addInCondition' : {'Type': 'WaitForEvents',
'Events' : jobINDict['Events']},
'addOutCondition' : {'Type': 'AddEvents',
'Events' : jobOUTDict['Events']}
}
check out lxml2json (disclosure: I wrote it).
it can convert any xml element into its json equivalent, and gives a measure of control over the structure of the output: including orderedDict, and which elements to render as list.
https://github.com/rparelius/lxml2json
Can you help me how I can pass list "some" into string "json_req" using format?
some = ["3874933","38423894"]
json_req='{"marketIds" : {},"priceProjection" : {"priceData" : ["EX_BEST_OFFERS"]}}'.format(some)
The result should be:
'{"marketIds" : ["3874933","38423894"],"priceProjection" : {"priceData" : ["EX_BEST_OFFERS"]}}'
At the moment I receive an error:
KeyError: '"marketIds" '
Thanks
If you have braces in a string you are formatting using format() you need to escape them by using double braces:
json_req='{{"marketIds" : {},"priceProjection" : {{"priceData" : ["EX_BEST_OFFERS"]}}}}'.format(some)
That being said, this whole method of generating the json makes me a little uneasy. It feels like you'd be better off using the json module with a native python object and using dumps at the end.
import json
some = ["3874933","38423894"]
template = {"marketIds" : some, "priceProjection" : {"priceData" : ["EX_BEST_OFFERS"]}}
json_req = json.dumps(template)
That'll lead to more flexible code if you need to change stuff later on.