there is part in my project using python where I get a JSON object and get those values and convert them to string.
My input will be:
data = {
"date":'12.04.2019',
"time":'06 am',
"event":'Complete project'
}
My output should be:
On 12.04.2019, 06 am the reminder is to Complete project
I have tried different methods to convert the JSON values to String but I get some sort of errors.
this's not a Json object, this is a dictionary so you can direct access the keys in it i.e.
res="On "+str(data['date'])+", "+str(data['time'])+"the reminder is to"+str(data['event'])
print(res)
you can also use date.get('date') to get the value of a specific key,they're both the same
for more info about dictionaries :https://www.w3schools.com/python/python_dictionaries.asp
for more info about Json Objects: https://www.w3schools.com/python/python_json.asp
As of python 3.6 you can use f strings:
print(f"On {data['date']}, {data['time']} the reminder is to {data['event']}")
If you don't have python 3.6 or above I suggest you to use formatting:
print("On %s, %s the reminder is to %s" %(data['date'], data['time'], data['event']))
data is not a JSON object it is a dictionary, so you can extract data using a keys.
Sample code:
data = {
"date":'12.04.2019',
"time":'06 am',
"event":'Complete project'
}
print("On "+ data["date"]+","+ data["time"] +" the reminder is to "+ data["event"])
Output:
On 12.04.2019,06 am the reminder is to Complete project
Related
I am altering a Lambda function (written in Python) that puts an item into a DynamoDB table. I have no issues when using the function to write to a DDB table with only a primary key, but get the following error after aligning attribute names and writing to a table with a partition and sort key:
An error occurred (ValidationException) when calling the PutItem operation:
One or more parameter values were invalid: Missing the key ID
Here is my function:
# import the json utility package since we will be working with a JSON object
import json
# import the AWS SDK (for Python the package name is boto3)
import boto3
# import two packages to help us with dates and date formatting
from time import gmtime, strftime
# create a DynamoDB object using the AWS SDK
dynamodb = boto3.resource('dynamodb')
# use the DynamoDB object to select our table
table = dynamodb.Table('PSCartTracking')
# store the current time in a human readable format in a variable
now = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
# define the handler function that the Lambda service will use as an entry point
def lambda_handler(event, context):
# extract values from the event object we got from the Lambda service and store in a variable
login = event['login']
computer = event['computer']
timestamp = event['timestamp']
# write name and time to the DynamoDB table using the object we instantiated and save response in a variable
response = table.put_item(
Item={
'ID': computer,
'Timestamp': timestamp,
'Login': login
})
# return a properly formatted JSON object
return {
'statusCode': 200,
'body': json.dumps(login + ' checked out ' + computer + ' on ' + now)
}
Keys for Table:
Partition key
ID (String)
Sort key
Timestamp (String)
I've been trying to read documentation to figure out what about my formatting might be preventing it from recognizing the sort key, but I'm pretty positive that is the part of the composite it is not seeing.
This is the payload for a request on python:
payload = "{\"depositCoin\":\"eth\",\"destinationCoin\":\"btc\"}"
I want to make the btc part variable, in other words, able to be changed depending on user input. I have tried replacing the string with a variable name but it doesn't work. I have also tried to replace it with a %d and then using % variable but it still does not work. Thanks for any help in advance!
Just use the json module to dump your dictionary into the proper format.
import json
payload = {"depositCoin": "eth", "destinationCoin": None}
coin = input()
print(coin)
# 'lite'
payload["destinationCoin"] = coin
json.dumps(payload)
'{"depositCoin": "eth", "destinationCoin": "lite"}'
I am trying to take user input, create a URI, and add it with a collection in Pymongo, but whenever I try to do this, the format gets messed up and I cant figure out how to fix it.
When running the line:
print(db.command("create", "storage", someStorage={ "URI": {FS_URI}}))
where "Storage" is the collection,
I want the object to be {"fs" : "something://a:b"} or {'fs' : 'something://a:b'}
FS_URI = ('\"fs\" : \"'+URI+'\"')
gives the error: Cannot encode object: {'"fs" : "something://a:b"'}
FS_URI = ("fs\" : \"%s" % URI)
gives the error" Cannot encode object: {'fs" : "something://a:b'}
FS_URI = ("fs\' : \'%s" % URI)
gives the error" Cannot encode object: {"fs' : 'something://a:b"}
The quotes are always unmatching, or have extra quotes around them.
I have tried the command with the actual URI in the quote format I want, and it runs perfectly.
I found that using a dict solved this problem, by changing
FS_URI = ("fs\" : \"%s" % URI)
to a JSON object rather than a string:
FS_URI = {"fs": "{}".format(URI)}
solved this problem
I have a Python3 script that takes an input HTML template and populates some data using this JSON and creates an output HTML.
Python Script -
with open('./jsonInp.json') as jsonFile:
jsonData = json.load(jsonFile)
inp_f = open('brandedTemplate.html', 'r+')
htmlInp = inp_f.read().format(links = jsonData['links'])
My JSON File -
{
"links" : {
"one" : "www.one.com",
"two" : "www.two.com",
}
}
Now using this in the input HTML like :
...
<a href={links.one}></a>
...
But this doesn't work. Neither does links['one'].
The JSON loading and everything works fine. I am also able to use arrays from .format function. Just can't find how to use this object anywhere. From type(jsonData['links']), I know its a Python dict.
Is there a way to use this in a html template?
Your jsonData variable is a python dict. To access values in the format mini language you need to use {my_dict[my_key]}. Note that the key is not enclosed in quotes.
To fix your example, the html input should be as follow:
...
<a href={links[one]}></a>
...
According to [Python]: Format examples, you should use (templates like):
<a href={links[one]}></a>
as html format specifier (since [Python]: json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw) returns a dict).
Example:
>>> json_dict
{'links': {'one': 'www.one.com', 'two': 'www.two.com'}}
>>> href_text
'<a href={links[one]}></a>'
>>> href_text.format(links=json_dict["links"])
'<a href=www.one.com></a>'
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