How to access a dictionary key inside a string - python

I have an API that expects to receive the data in a string format. The data looks like this:
test = """{"API_name":"getScenario","token":"1112223333","clientId":"1","clientEmail":"yup#nope#gmail.com", "more": "hello"}"""
I am used to accessing the dictionary keys rather easily test[token] but in this case it is all encased in a multi-line string.
How is this supposed to be accessed?

Parse the string and then find access by key
import json
data = json.loads(test)
data['API_name']

Related

Convert Json format String to Link{"link":"https://i.imgur.com/zfxsqlk.png"}

I try to convert this String to only the link: {"link":"https://i.imgur.com/zfxsqlk.png"}
I'm trying to create a discord bot, which sends random pictures from the API https://some-random-api.ml/img/red_panda.
With imageURL = json.loads(requests.get(redpandaurl).content) I get the json String, but what do I have to do that I only get the Link like this https://i.imgur.com/zfxsqlk.png
Sorry if my question is confusingly written, I'm new to programming and don't really know how to describe this problem.
You can simply do this:
image_url = requests.get(your_api_url).json()["link"]
Directly use requests.json(), no need to load the string with json.loads and other manual stuff.
What you get from json.loads() is a Python dict. You can access values in the dict by specifying their keys.
In your case, there is only one key-value pair in the dict: "link" is the key and "https://i.imgur.com/zfxsqlk.png" is the value. You can get the link and store it in the value by appending ["link"] to your line of code:
imageURL = json.loads(requests.get(redpandaurl).content)["link"]

Parsing JSON output in Robot framework [Tried most options in the forum]

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.

Parse single qouted dictionary key and value in Python

I have a Python dictionary
original_dict={'body': '{"infra":["dev4","elk"],{"type":"file_integrity"}'}
I want to be able to parse original_dict keys and values as a normal dictionary which I am not able to do now because 'body' key has a a dictionary casted as string and therefore I am not refer to any of it's keys. So I should be able to say:
infra=original_dict['body]['infra']
Can anyone help me out with this.
First of all, you are missing a curly brace in the original_dict.
Here is an example of converting a string into a dictionary.
import json
original_dict={'body':'{"infra":["dev4","elk"],"type":"file_integrity"}'}
original_dict['body'] = json.loads(original_dict['body'])
infra=original_dict['body']['infra']
print(infra)
Output : ['dev4', 'elk']
You can use ast too:)
import ast
original_dict = {'body': '{"infra":["dev4","elk"],"type":"file_integrity"}'}
original_dict['body'] = ast.literal_eval(original_dict['body'])

Using A Python List or String in Dictionary Lookup?

Use Case
I am making a factory type script in Python that consumes XML and based on that XML, returns information from a specific factory. I have created a file that I call FactoryMap.json that stores the mapping between the location an item can be found in XML and the appropriate factory.
Issue
The JSON in my mapping file looks like:
{
"path": "['project']['builders']['hudson.tasks.Shell']",
"class": "bin.classes.factories.step.ShellStep"
}
path is where the element can be found in the xml once its converted to a dict.
class is the corresponding path to the factory that can consume that elements information.
In order to do anything with this, I need to descend into the dictionaries structure, which would look like this if I didn't have to draw this information from a file(note the key reference = 'path' from my json'):
configDict={my xml config dict}
for k,v in configDict['project']['builders']['hudson.tasks.Shell'].iteritems():
#call the appropriate factory
The issue is that if I look up the path value as a string or a list, I can not use it in 'iteritems'():
path="['project']['builders']['hudson.tasks.Shell']" #this is taken from the JSON
for k,v in configDict[path].iteritems():
#call the appropriate factory
This returns a key error stating that I can't use a string as the key value. How can I used a variable as the key for that python dictionary?
You could use eval:
eval( "configDict"+path )
You can use the eval() function to evaluate your path into an actual dict object vs a string. Something like this is what I'm referring to:
path="['project']['builders']['hudson.tasks.Shell']" #this is taken from the JSON
d = eval("configDict%s" % path)
for k,v in d.iteritems():
#call the appropriate factory

Pass a variable to extract from JSON String in Python?

I have below JSON String. Now I want to extract each individual field from that JSON string.
So I decided to create a method parse_json which will accept a variable that I want to extract from the JSON String.
Below is my python script -
#!/usr/bin/python
import json
jsonData = '{"pp": [0,3,5,7,9], "sp": [1,2,4,6,8]}'
def parse_json(data):
jj = json.loads(jsonData)
return jj['+data+']
print parse_json('pp')
Now whenever I an passing pp to parse_json method to extract its value from the JSON String, I always get the error as -
return jj['+data+']
KeyError: '+data+'
Any idea how to fix this issue? As I need to pass the variable which I am supposed to extract from the JSON String?
You probably just want this:
return jj[data]
Your code is trying to look up a key named literally '+data+', when instead what you want to do is look up the key with a name of the function's parameter.
Just use data parameter itself.
Replace following line:
return jj['+data+'] # lookup with `+data+`, not `pp`
with:
return jj[data]

Categories

Resources