How to concatenate a json.dumps output with a string - python

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.

Related

Python Dictionary as Valid jSon?

in python I have:
dict = {}
dict['test'] = 'test'
when I print I get:
{'test':'test'}
How can I make it like this:
{"test":"test"}
Please Note, replace won't work as test may be test't...
I tried:
dict = {}
dict["test"] = "test"
You can use json.dumps()
For example, if you use print json.dumps(dict) you should get the desired output.
Additionally, as suggested in a different related question, you may construct your own version of a dict with special printing:
How to create a Python dictionary with double quotes as default quote format?

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

Using a Variable in REQUESTS in Python

I've got an API request to make that involves passing some variables from user input and a config file to a filter expression contained in a dictionary.
The API uses hashes in its structure to wrap stings by default, although I can specify another string wrapping indicator if need be via a separate request. As is, what I need to do is below, basically.
I can't figure out the syntax to get those strings to populate the values between the wrapper # signs. Lots of questions about this, but none addressing the basic syntax without additional functionality, as far as I can tell.
import config
import requests
var1 = **the result of user input, a string**
var2 = **a value from a config file, also a string**
url = (config.api_url)
payload = {
'key':config.api_key,
'Operation':'GetEntities',
'Entity':'my_entity',
'Attributes':'my_attribute1,my_attribute2',
'Filter':'api_var1<eq>#var1# AND api_var2<eq>#var2#'}
response = requests.post(url,payload)
They key point is here:
'Filter':'api_var1<eq>#var1# AND api_var2<eq>#var2#'
So if var1 = '1234' and var2 = '4321' I need it to be the equivalent of:
'Filter':'api_var1<eq>#1234# AND api_var2<eq>#4321#'
As far as I understand you want something like
'Filter':'api_var1<eq>#{0}# AND api_var2<eq>#{1}#'.format(var1, var2)}
or
'Filter':'api_var1<eq>#%s# AND api_var2<eq>#%s#' % (var1, var2)}

Python elasticsearch-dsl sorting with multiple fields

I'm trying to form the command for sorting using elasticsearch-dsl. However I have trouble passing the variable in correct format in.
The format should be
s=Search()
s = s.sort({"time":{"order":"asc"}}, {"anoter_field":{"order":"desc"}})
s.execute()
The problem is I'm trying to put {"time":{"order":"asc"}}, {"anoter_field":{"order":"desc"}} as a variable, but I can't seem to get this in the right syntax. I tried using dict, list, and string, and none seems to work.
My input would be a dict that looks like
input = {"time":"asc", "another_field":"desc"}
data_input = {"time":"asc", "another_field":"desc"}
args = [{k:{'order':v}} for k,v in data_input.items()]
s.sort(*args)
I guess is what you are asking? Its hard to tell ...

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