i want to append below json with the data
meta = [{
"output_metadata": {
"api_URL": apiURL,
"query_execution_time": queryExecTime,
"api_execution_time": apiExecTime,
}
}]
jsondata = json.dumps([dict(ix) for ix in Data], default=str)
json data:
{"data": [{"id": "1234", "name": "jhon", "dept": "APA"}]}
meta.append(jsondata)
expected result:
{"output_metadata": {"api_url": "xxxxx", "query_execution_time":"xxxxx", "api_execution_time":"xxxxx"}},{"data": "[{"id": "1234", "name": "jhon", "dept": "APA"}]}
output:
{"output_metadata": {"api_url": "XXXXXX", "query_execution_time": "XXXXXX", "api_execution_time":"XXXXXX" }},{"data": "[{"\id": "1234\", "\name": "\jhon", "\dept": "\APA"}]}
How to remove \ from the final output?
If this thing you wrote above is python the meta variable you create is invalid because before every " you should use an escape character and every time you go in a new line. For example you should write:
meta = ["{\
\"output_metadata\": {\
\"api_URL\": apiURL,\
\"query_execution_time\": queryExecTime,\
\"api_execution_time\": apiExecTime, \
}\
}"]
data = ["{\"data\": {\"id\": \"1234\", \"name\": \"jhon\", \"dept\": \"APA\"}]}"]
meta.append(data)
Where you handle the json's as strings and then append them in one list. Is this what you want?
EDIT: if you run something like
data = [{"id": 1234, "name": "jhon", "dept": "APA" }]
jdata= json.dumps([dict(ix) for ix in data], default=str)
apiURL = 'url'
queryExecTime = 1
apiExecTime = 1
meta = [{ "output_metadata": { "api_url": apiURL,
"query_execution_time": queryExecTime,
"api_execution_time": apiExecTime, } }]
jdata = { "data": jdata }
meta.append(jdata)
res = json.dumps(meta)
print(res)
the result will be:
'[{"output_metadata": {"api_url": "url", "query_execution_time": 1, "api_execution_time": 1}}, {"data": "[{\\"id\\": 1234, \\"name\\": \\"jhon\\", \\"dept\\": \\"APA\\"}]"}]'
The \ are used as escape characters for the ". You see the result as a literal string.
Related
resp = {
"Name": "test",
"os": "windows",
"Agent": {
"id": "2",
"status": [
{
"code": "123",
"level": "Info",
"displayStatus": "Ready",
"message": "running",
"time": "2022-01-18T09:51:08+00:00"
}
]
}
I am trying to get the time value from the JSON.
I tried the below code but faced error with dict
resp1 = json.loads(resp)
resp2 = resp1.values()
creation_time = resp2.get("Agent").get("status")
val= creation_time["time"]
print(val) ## Thrwoing error as dict_values has no 'get'
Any suggestion on python how to take this time values
Few problems I noticed
You are trying to load a Dict type using the json's loads function which is supposed to get a string in json format (ex: '{ "name":"John", "age":30, "city":"New York"}')
You tried to access resp2 before declaration (I guessed you meant "resp1?")
You're using resp3 without declaration.
You are missing }
You don't need the .value() function because it will return a list.
Also creation time is a list with one object, so you need to access it too.
Considering all this, you can change it as follows:
import json
resp = '{ "Name": "test", "os": "windows","Agent": {"id": "2","status": [{"code": "123","level": "Info","displayStatus": "Ready","message": "running","time": "2022-01-18T09:51:08+00:00"}]}}'
resp1 = json.loads(resp)
creation_time = resp1.get("Agent").get("status")
val= creation_time[0]["time"]
print(val)
You just need to access the dicts using [] like so:
resp = {"Name": "test", "os": "windows", "Agent": {"id": "2","status": [{"code": "123","level": "Info","displayStatus": "Ready","message": "running","time": "2022-01-18T09:51:08+00:00"}]}}
creation_time = resp["Agent"]["status"]
val= creation_time[0]["time"]
print(val)
Output:
2022-01-18T09:51:08+00:00
I have a dictionary below:
event = {
"body-json": {},
"params": {
"path": {
"matchphrase": "term"
},
"querystring": {
"dataproduct.keyword": "health"
},
"header": {
"Accept": "application/json"
}
},
"resource-path": "/{matchphrase}"
}
I would like to access the above event dictionary keys & values and frame a new dictionary as follows:
{"query": {"term" : {"dataproduct.keyword": "health"}}}
Here is the code what I tried:
a = event['params']['path']['matchphrase'] #term
b = list(event['params']['querystring'].keys())[0] #dataproduct.keyword
c = list(event['params']['querystring'].values())[0] #health
body=f"{query: {{a} : {{b}: {c}}}}"
print(body)
Am I missing something ?
This should work :
body = {"query":{str(a):{str(b):str(c)}}}
print(body)
The escaping is wrong.
Try this instead:
body = f'{{"query": {{{a!r}: {{{b!r}: {c!r}}}}}}}'
I've also added !r which will return the real representation (repr) of the object (so you don't need to artificially add quotes).
you can create a dictionary and then get a string version of it using json.dumps.
import json
event = {
"body-json": {},
"params": {
"path": {"matchphrase": "term"},
"querystring": {"dataproduct.keyword": "health"},
"header": {"Accept": "application/json"},
},
"resource-path": {"matchphrase}"},
}
a = event["params"]["path"]["matchphrase"] # term
b = list(event["params"]["querystring"].keys())[0] # dataproduct.keyword
c = list(event["params"]["querystring"].values())[0] # health
result = {"query": {a: {b: c}}}
print(json.dumps(result))
Output:
{"query": {"term": {"dataproduct.keyword": "health"}}}
I have a list that has a couple of dicts inside and they are all separated with a comma ",". What is happening is that when i create this list i am adding , inside a for loop, a comma after every dict to separate them but it is also adding a last comma after the last dictionary. Something like:
"guests": [{
"age": "18",
"birthDate": null,
"emailAddress": null,...
....
"name": {
"prefix": "Mr.",
"firstName": "James",
"middleName": "",
"lastName": "Jones",
"suffix": ""
}
},----------------------------->This comma
]
I think that last comma is creating some issues when trying to make a post request to the web service. So, How can i delete just that last comma inside the list?
Thanks
Edit
The creation of the list is happening inside a for loop. Something like:
participants_body = ''
for guest in guests_info:
post_body = '{"profile": {"name": {"title": "' + guest["title"] + '","firstName": "' \
+ guest["first_name"] + '","lastName": "' + guest["last_name"] \
+ '"},"age": 18},"preferences": {"avatarIdentifier": "15655408","favoriteCharacterIdentifier":' \
' "15655408"},"friendsAndFamily": {"groupClassification": {"name": "TRAVELLING_PARTY"},' \
'"accessClassification": {"name": "PLAN_VIEW_SHARED"}}}'
response = requests.post(url, data=post_body, headers=headers)
json_response = response.json()
participants_body = '{"age": "' + str(json_response["profile"]["age"]) + '","birthDate": null,"emailAddress": null,' \
'"phone": null,"primary": false,"swid": null,"guid": "' + guid + '","gender": null,"type": null,' \
'"participantId": "' + p_id + '","profileLink": "https://env5.nge.api.go.com' + profileLink + '", ' \
'"infantSittingWithAdult": false,"avatar": null,"itemsAssigned": ' \
'["' + item_id + '"],"address": null,"phoneNumber": null,"dataType": "basic",' \
'"isRoomAssigned": true,"isVacationOfferAssigned": true,"ageGroup": "","name": {' \
'"prefix": "' + json_response["profile"]["name"]["title"] + '","firstName": "' \
+ json_response["profile"]["name"]["firstName"] + '","middleName": "","lastName": "' \
+
json_response["profile"]["name"]["lastName"] + '","suffix": ""}},'------------> HERE IS THE COMA
post_body_participants += participants_body
So, that´s why i´m getting the coma. I just need to delete it after the for loop
EDIT
I´m creating a Post message and i´m getting this error:
{u'errors': [{u'message': u'org.codehaus.jackson.map.JsonMappingException: Can not instantiate value of type [simple type, class com.disney.wdpro.service.booking.webservice.resource.ParticipantWithAssignmentResourceCollection] from JSON String; no single-String constructor/factory method'}]}
I read a couple of SO questions and they mentioned that maybe this is happening because an error with the json format.
Also i can see how the body of the post is created in other messages in the logs and that last comma is not there, so maybe that´s what´s happening
I'm not sure why you're creating this as a string. You'll be happier to create the dicts as dicts. The code is much more readable, which will help you when you have to change it later. Besides that, it will eliminate little typo bugs like you're experiencing.
post_body = {
'profile': {
'name': {
'title': guest['title'],
'firstName': guest['first_name'],
'lastName': guest['last_name'] },
'age': 18 },
'preferences': {
'avatarIdentifier': 15655408,
'favoriteCharacterIdentifier': 15655408 },
'friendsAndFamily': {
'groupClassification': {
'name': 'TRAVELLING_PARTY' },
'accessClassification': {
'name': 'PLAN_VIEW_SHARED' }
}
}
It's easy to turn that dict into a JSON string:
import json
post_body = json.dumps(post_body)
You can do the same thing with creating a list from the participants_body response. Just create the one dict as above, and append it with post_body_participants.append(participants_body). Again, you can access that list in the form of a JSON string with json.dumps(post_body_participants).
You will save yourself a great deal of pain if you use the built in json encoders/decoders to build your json strings. Building them by hand is error prone. Why not stand on the shoulders of giants?
import requests
import json
participants =[]
for guest in guests_info:
#Build Python objects and not json strings
#Convert it all to json later
post_body = {
'profile': {
'name': {
'title': guest['title'],
'firstName': guest['first_name'],
'lastName': guest['last_name'] },
'age': 18 },
'preferences': {
'avatarIdentifier': 15655408,
'favoriteCharacterIdentifier': 15655408 },
'friendsAndFamily': {
'groupClassification': {
'name': 'TRAVELLING_PARTY' },
'accessClassification': {
'name': 'PLAN_VIEW_SHARED' }
}
}
#The requests module has json encoding/decoding built in
response = requests.post(url, json=post_body, headers=headers)
#Or you could use Python's built in json module
#response = requests.post(url, data=json.dumps(post_body), headers=headers)
json_response = response.json() #This decodes the json string in the response to a Python object
participant = {
"age": json_response["profile"]["age"],
"birthDate": None,
"emailAddress": None,
"phone": None,
"primary": False,
"swid": None,
"guid": guid,
"gender": None,
"type": None,
"participantId": p_id,
"profileLink": "https://env5.nge.api.go.com" + profileLink + ,
"infantSittingWithAdult": False,
"avatar": None,
"itemsAssigned": [item_id],
"address": None,
"phoneNumber": None,
"dataType": "basic",
"isRoomAssigned": True,
"isVacationOfferAssigned": True,
"ageGroup": "",
"name": {
"prefix": json_response["profile"]["name"]["title"],
"firstName": json_response["profile"]["name"]["firstName"],
"middleName": "",
"lastName": json_response["profile"]["name"]["lastName"],
"suffix": ""}
}
}
participants.append(participant)
I'm using the following python code to connect to a jsonrpc server and nick some song information. However, I can't work out how to get the current title in to a variable to print elsewhere. Here is the code:
TracksInfo = []
for song in playingSongs:
data = { "id":1,
"method":"slim.request",
"params":[ "",
["songinfo",0,100, "track_id:%s" % song, "tags:GPASIediqtymkovrfijnCYXRTIuwxN"]
]
}
params = json.dumps(data, sort_keys=True, indent=4)
conn.request("POST", "/jsonrpc.js", params)
httpResponse = conn.getresponse()
data = httpResponse.read()
responce = json.loads(data)
print json.dumps(responce, sort_keys=True, indent=4)
TrackInfo = responce['result']["songinfo_loop"][0]
TracksInfo.append(TrackInfo)
This brings me back the data in json format and the print json.dump brings back:
pi#raspberrypi ~/pithon $ sudo python tom3.py
{
"id": 1,
"method": "slim.request",
"params": [
"",
[
"songinfo",
"0",
100,
"track_id:-140501481178464",
"tags:GPASIediqtymkovrfijnCYXRTIuwxN"
]
],
"result": {
"songinfo_loop": [
{
"id": "-140501481178464"
},
{
"title": "Witchcraft"
},
{
"artist": "Pendulum"
},
{
"duration": "253"
},
{
"tracknum": "1"
},
{
"type": "Ogg Vorbis (Spotify)"
},
{
"bitrate": "320k VBR"
},
{
"coverart": "0"
},
{
"url": "spotify:track:2A7ZZ1tjaluKYMlT3ItSfN"
},
{
"remote": 1
}
]
}
}
What i'm trying to get is result.songinfoloop.title (but I tried that!)
The songinfo_loop structure is.. peculiar. It is a list of dictionaries each with just one key.
Loop through it until you have one with a title:
TrackInfo = next(d['title'] for d in responce['result']["songinfo_loop"] if 'title' in d)
TracksInfo.append(TrackInfo)
A better option would be to 'collapse' all those dictionaries into one:
songinfo = reduce(lambda d, p: d.update(p) or d,
responce['result']["songinfo_loop"], {})
TracksInfo.append(songinfo['title'])
songinfo_loop is a list not a dict. That means you need to call it by position, or loop through it and find the dict with a key value of "title"
positional:
responce["result"]["songinfo_loop"][1]["title"]
loop:
for info in responce["result"]["songinfo_loop"]:
if "title" in info.keys():
print info["title"]
break
else:
print "no song title found"
Really, it seems like you would want to have the songinfo_loop be a dict, not a list. But if you need to leave it as a list, this is how you would pull the title.
The result is really a standard python dict, so you can use
responce["result"]["songinfoloop"]["title"]
which should work
I'm reading in a JSON string which is littered with u'string' style strings. Example:
[
{
"!\/award\/award_honor\/honored_for": {
"award": {
"id": "\/en\/spiel_des_jahres"
},
"year": {
"value": "1996"
}
},
"guid": "#9202a8c04000641f80000000003a0ee6",
"type": "\/games\/game",
"id": "\/en\/el_grande",
"name": "El Grande"
},
{
"!\/award\/award_honor\/honored_for": {
"award": {
"id": "\/en\/spiel_des_jahres"
},
"year": {
"value": "1995"
}
},
"guid": "#9202a8c04000641f80000000000495ec",
"type": "\/games\/game",
"id": "\/en\/settlers_of_catan",
"name": "Settlers of Catan"
}
]
If I assign name = result.name. Then when I log of pass that value to a Django template, it displays as u'Dominion'
How do I format it to display as Dominion?
++ UPDATE ++
I think the problem has to do with printing values from a list or dictionary. For example:
result = freebase.mqlread(query)
games = {}
count = 0
r = result[0]
name = r.name
games["name"] = name,
self.response.out.write(games["name"])
self.response.out.write(name)
This displays as:
(u'Dominion',) // saved response to dictionary, and then printed
Dominion // when calling the value directly from the response
I need to iterate through an array of JSON items and the values are being shown with the unicode. Why?
The comma at the end of games["name"] = name, makes it a 1-tuple. Remove it.
>>> # example
>>> s = u"Jägermütze"
>>> s.encode("utf-8")
'J\xc3\xa4germ\xc3\xbctze'
>>> print s.encode("utf-8") # on a utf-8 terminal
Jägermütze
Don't know much about Django, but not accepting snicode strings seems unpythonic to me.
You can use str(your string) to do this.