Pass a variable to extract from JSON String in Python? - 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]

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"]

How to concatenate a json.dumps output with a string

Summary
I am attempting to concatenate the output of json.dumps - converting part dictionary variable, that has been passed from a client to a server, to a string - with a string, before passing it to a variable where it defines the name of a mbox file to be accessed.
Variables defined
The below variables are defined in the server's code.
recp_encoded = receive_message(client_socket)
recp = format(recp_encoded['data'].decode('utf-8'))
Variables accessed
json_user = (json.dumps(recp) + '.mbox')
print(json_user)
mailbox_name = str(json_user)
mbox = mailbox.mbox(mailbox_name)
mbox.lock()
However, the above code does not work as it formats the string as:
"user2".mbox'
Rather than the:
'user2.mbox'
That I need. In short, how do I fix the above to format the string to how I need it?
It seems that recp is a simple string type. Why not use the variable as given?
json_user = recp_encoded['data'].decode('utf-8') + '.mbox'
Will this not give you want you need? It doesn't seem that recp is sent as a JSON.

How to access a dictionary key inside a string

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']

Trying to use a JSON object as a argument (Python)

I've written some code that converts a JSON object to an iCalendar (.ics) object and now I am trying to test it. The problem is that I can't figure out how to create a generic JSON object to use as the parameter. Some of my attempts are as follows:
# 1
obj_json = u'sample json data in string form'
obj = json.loads(obj_json)
# 2
# I'm not sure about this very first line. My supervisor told me to put it in but he
# has a very heavy accent so I definitely could have heard him incorrectly.
input.json
with open('input.json') as f:
obj = json.loads(f.read())
Try,
import json
some_dict = {'id': 0123, 'text': 'A dummy text'}
dummy_json = json.dumps(some_dict)
Now, feed your dummy json to your function. i.e.
'{"text": "A dummy text", "id": 83}'
You can do dumps with a string object too.
See pnv's answer, but you probably don't need to dump it. Just use a dictionary, as pnv did, and pass that into whatever you need to. Unless you are about to pass your json object over the wire to something, I don't know why you'd want to dump it.
I would've added this as a comment, but no rep, yet. :)

python code to get values from json data

Am trying to extract command line arguments passed in python
cmdargs = str(sys.argv)
print cmdargs
it prints
['E:/omation.py', '{"command":"sel_media","value":"5X7_phot
o_paper.png"},{"command":"tray","value":"4X6_photo_paper.png"}']
from this how can i extract command and values .
i dont knoe how to loop this array and get the commnd and value values.plese help
Note: i also want to discard the first value 'E:/omation.py'
You can use Python utils to parse json strings:
import json
examples = json.loads('['+cmdargs[1]+']')
The first import loads json utilities for python. Then, you can parse a json string into a Python dictionary by using json.loads. In the example, I have parsed one of your json strings into a python dictionary. Remember to add '[' and ']' to convert your string to a valid json array. Then, you can get a command and a value like :
print(examples[0]['command'])
print(examples[0]['value' ])
The example you give shows two json objects in the second element of the list cmdargs. Probably the easiest way to capture that case would be to enclose that second argument in square braces, which would make it legal JSON, then loop through the resulting list:
import json
a = json.loads('['+cmdargs[1]+']')
for p in a:
print "command is ", p['command']
print "value is ", p['value']
This is specific to the example you showed, you may need to make it more robust for your purposes.
Your input is not valid JSON. You must find a way to pass the arguments as separate, valid JSON objects. Then you can do this:
# j.py
import json
import sys
print(sys.argv)
for arg in sys.argv[1:]:
j = json.loads(arg)
print(j.get("command"))
print(j.get("value"))
Usage could be:
$ python3 j.py '{"command":"sel_media","value":"5X7_photo_paper.png"}' '{"command":"tray","value":"4X6_photo_paper.png"}'
['j.py', '{"command":"sel_media","value":"5X7_photo_paper.png"}', '{"command":"tray","value":"4X6_photo_paper.png"}']
sel_media
5X7_photo_paper.png
tray
4X6_photo_paper.png

Categories

Resources