I am using python url library to get json response from spatial reference website.This is my code. I get response_read="u'{\'type\': \'EPSG\', \'properties\': {\'code\': 102646}}'" but i need this response in this form:"{'type': 'EPSG', 'properties': {'code': 102646}}". How i achieve output in this form?
headers = {'User-Agent': 'Mozilla/5.0'}
req = urllib2.Request("http://spatialreference.org/ref/esri/"nad-1983-stateplane-california-vi-fips-0406-feet"/json/", None, headers)
response = urllib2.urlopen(req)
response_read = response.read().decode('utf-8')
result = json.dumps(response_read)
epsg_json = json.loads(result)
epsg_code = epsg_json['properties']['code']
return epsg_code
you need to first use dumps then loads
json_data = json.dumps(response_read)
json_without_slash = json.loads(json_data)
I am not very sure your is a function or not. Anyways, the response you receive is having the literal character ' and you need to replace it with ".
Here is the working code:
import urllib2,json
headers = {'User-Agent': 'Mozilla/5.0'}
req = urllib2.Request("http://spatialreference.org/ref/esri/nad-1983-stateplane-california-vi-fips-0406-feet/json/", None, headers)
response = urllib2.urlopen(req)
response_read = response.read()
epsg_json = json.loads(response_read.replace("\'", '"'))
epsg_code = epsg_json['properties']['code']
print(epsg_code)
Hope this helps.
Related
I'm trying to put python objects into a JSON file by getting the API from one of the sites but somehow when I run the code nothing has been put in the JSON file. API is working well, as well when I print out the code by json.load I get the output but I have no idea why does dump doesn't work.
here is my code:
from django.shortcuts import render
import requests
import json
import datetime
import re
def index(request):
now = datetime.datetime.now()
format = "{}-{}-{}".format(now.year, now.month, now.day)
source = []
author = []
title = []
date = []
url = "http://newsapi.org/v2/everything"
params = {
'q': 'bitcoin',
'from': format,
'sortBy': 'publishedAt',
'apiKey': '1186d3b0ccf24e6a91ab9816de603b90'
}
response = requests.request("GET", url, params=params)
for news in response.json()['articles']:
matching = re.match("\d+-\d+-\d+", news['publishedAt'])
if format == matching.group():
source.append(news['source'])
author.append(news['author'])
title.append(news['title'])
date.append(news['publishedAt'])
data = \
{
'source': source,
'author': author,
'title': title,
'date': date
}
with open('data.json', "a+") as fp:
x = json.dump(data, fp, indent=4)
return render(request, 'news/news.html', {'response': response})
After calling a MS Graph API using HttpBuilder which return user information, I would like to return the Id attribute of the Json response
The complete Json response is as below :
{
#odata.context=https://graph.microsoft.com/v1.0/$metadata#users,
value=[{
businessPhones=[],
displayName=Serge Cal GMAIL,
givenName=null,
jobTitle=null,
mail=user1.tom#gmail.com,
mobilePhone=null,
officeLocation=null,
preferredLanguage=null,
surname=null,
userPrincipalName=user1.tom_gmail.com#EXT##SCALDERARA.onmicrosoft.com,
id=253bca1d-6c03-441f-92e4-e206c7d180f7
}]
}
For doing so I have a groovy method define as below :
public String getUserIdByEmailQuery(String AuthToken,String userEmail){
String _userId
def http = new HTTPBuilder(graph_base_user_url +"?")
http.request(GET) {
requestContentType = ContentType.JSON
uri.query = [ $filter:"mail eq '$userEmail'".toString() ]
headers.'Authorization' = "Bearer " + AuthToken
response.success = { resp, json ->
**_userId=json["value"]["id"]**
}
// user ID not found : error 404
response.'404' = { resp ->
_userId = 'Not Found'
}
}
_userId
}
With this update the reponse value is [xxx-xxx-xxx-xxx-xxx-], which is correct excpet that it suround the value with []
Any idea ?
regards
The original problem was caused by the wrong expression to get the id and since you have got the id list [xxx-xxx-xxx-xxx, xxx-xxx-xxx-xxx, ...] by json["value"]["id"], so you just need to use json["value"]["id"][0] to get the first id of the list.
And this expression json["value"][0]["id"] might also work.
Update:
You can use groovy.json.JsonSlurper to help you parse the json and get the id value.
import groovy.json.JsonSlurper
JsonSlurper slurper = new JsonSlurper()
Map parsedJson = slurper.parseText(json)
String idValue = parsedJson.value[0].id
Further to my earlier post yesterday: Post request to external Rest Service using Django - use returned json to update model
I have managed to post data to camunda using Django - request.post. Using the following script:
payload = "{\n \"businessKey\": \"SomeValue\",\n \"variables\": {\n \"Organisation_ID\": {\n \"value\": \"SOmeUUID\",\n \"type\": \"String\"\n },\n \"UserID\": {\n \"value\":\"Some User ID\",\n \"type\": \"String\"\n }\n }\n}"
However when I start to use variables from the form and format my payload using
class StartProcessView(View):
template_name = 'startdeliveryphase.html'
def get(self,request, *args, **kwargs):
form = IntStartDeliveryPhase
return render(request, self.template_name,{'form':form})
def post(self,request, *args, **kwargs):
form = IntStartDeliveryPhase(request.POST or None)
if form.is_valid():
data = form.cleaned_data
OrganisationID = data['Form_Field_OrganisationID']
UserID = data['Form_Field_User_ID']
BusinessKey = data['Form_Field_Business_Key']
url = "http://localhost:8080/engine-rest/process-definition/key/Process_B_PerProject/start"
payload = {"businessKey":BusinessKey,"variables":[{"Organisation":[{"value":OrganisationID, "type":"String"}]},[{"Startedby":[{"value":UserID,"type":"String"}]}]]}
headers = {
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data = payload)
#print(repsonse.errors)
print(response.text.encode('utf8'))
return render(request)
else:
return render(request,self.template_name,{'form':form})
I get an error from the camunda engine:-
b'{"type":"JsonParseException","message":"Unrecognized token \'businessKey\': was expecting (\'true\', \'false\' or \'null\')\\n at [Source: (org.camunda.bpm.engine.rest.filter.EmptyBodyFilter$1$1); line: 1, column: 13]"}'
the local vars shows the following:
▼ Local vars
Variable Value
BusinessKey
'1qaz'
OrganisationID
<Organisation: Some Local Authoristy>
UserID
<Actor_User: me#me.com>
args
()
data
{'Form_Field_Business_Key': '1qaz',
'Form_Field_CamundaInstanceID': 'sss',
'Form_Field_Camunda_HRef': 'ss',
'Form_Field_Camunda_TenantID': '22',
'Form_Field_DateCreated': datetime.datetime(2020, 4, 23, 19, 22, 30, tzinfo=<StaticTzInfo 'GMT'>),
'Form_Field_OrganisationID': <Organisation: Some Local Authoristy>,
'Form_Field_User_ID': <Actor_User: me#me.com>}
form
<IntStartDeliveryPhase bound=True, valid=True, fields=(Form_Field_OrganisationID;Form_Field_DateCreated;Form_Field_CamundaInstanceID;Form_Field_Camunda_HRef;Form_Field_Camunda_TenantID;Form_Field_User_ID;Form_Field_Business_Key)>
headers
{'Content-Type': 'application/json'}
kwargs
{}
payload
{'businessKey': '1qaz',
'variables': [{'Organisation': [{'type': 'String',
'value': <Organisation: Some Local Authoristy>}]},
[{'Startedby': [{'type': 'String',
'value': <Actor_User: me#me.com>}]}]]}
request
<WSGIRequest: POST '/bimProcess/'>
response
<Response [400]>
self
<bimProcess.views.StartProcessView object at 0x055B7898>
url
'http://localhost:8080/engine-rest/process-definition/key/Process_B_PerProject/start'
How do I get the correct format as required by camunda into which I can insert my variables with the required double quotes
EDIT Yay - I have finally got the correct sequence!!!!
def post(self,request, *args, **kwargs):
form = IntStartDeliveryPhase(request.POST or None)
if form.is_valid():
data = form.cleaned_data
OrganisationID = str(data['Form_Field_OrganisationID'])
UserID = str(data['Form_Field_User_ID'])
BusinessKey = data['Form_Field_Business_Key']
url = "http://localhost:8080/engine-rest/process-definition/key/Process_B_PerProject/start"
payload = {"businessKey":BusinessKey,"variables":{"Organisation":{"value":OrganisationID, "type":"String"},"Startedby":{"value":UserID,"type":"String"}}}
headers = {
'Content-Type': 'application/json'
}
payload2 = json.dumps(payload)
print (payload2)
response = requests.request("POST", url, headers=headers, data=payload2)
#print(repsonse.errors)
print(response.text.encode('utf8'))
return render(request)
else:
return render(request,self.template_name,{'form':form})
Now for the next questions:
1) I get a response from Camunda as a 200: the payload back from the post request needs to go back into the form data where it can then be saved without user interruption.
2)I am doing a post self on this form - what is the best way of achieving the sequence flow? should I do a redirect and pass the data through or is there a more efficient way? Also is there a better way to achieve the view.py than I have posted which is more efficient?
def post(self,request, *args, **kwargs):
form = IntStartDeliveryPhase(request.POST or None)
if form.is_valid():
data = form.cleaned_data
OrganisationID = str(data['Form_Field_OrganisationID'])
UserID = str(data['Form_Field_User_ID'])
BusinessKey = data['Form_Field_Business_Key']
url = "http://localhost:8080/engine-rest/process-definition/key/Process_B_PerProject/start"
payload = {"businessKey":BusinessKey,"variables":{"Organisation":{"value":OrganisationID, "type":"String"},"Startedby":{"value":UserID,"type":"String"}}}
headers = {
'Content-Type': 'application/json'
}
payload2 = json.dumps(payload)
print (payload2)
response = requests.request("POST", url, headers=headers, data=payload2)
#print(repsonse.errors)
print(response.text.encode('utf8'))
return render(request)
else:
return render(request,self.template_name,{'form':form})
I'm trying to post json in Lua using cURL. I can't find any example online.
Something like this:
c = curl.easy{
url = "http://posttestserver.com/post.php",
-- url = "http://httpbin.org/post",
post = true,
httppost = curl.form{
data = "{}",
type = "application/json",
},
}
t = {}
c:perform{
writefunction = function(s)
t[#t+1] = s
end
}
c:close()
Try this one.
local cURL = require "cURL"
c = cURL.easy{
url = "http://posttestserver.com/post.php",
post = true,
httpheader = {
"Content-Type: application/json";
};
postfields = "{}";
}
c:perform()
I have a Django app. In the view I call another function (in stats.py) which then makes a HTTP POST.
views.py
from stats import Stat
a = Stat(example="12345")
a.use(id='query')
stats.py
self.data = { example : "12345" }
req = urllib2.Request(api_url)
req.add_header('Content-Type', 'application/json')
response = urllib2.urlopen(req, json.dumps(self.data))
The problem that occurs is that I get the error,
<django.utils.functional.SimpleLazyObject object at 0x2b4d1fe47650> is not JSON serializable
Django Traceback
From looking at the Django Traceback I get the following,
/prod/tools/lx/views.py in update_input
a.use(id='query')
...
/prod/tools/main/stats.py in log_use
response = urllib2.urlopen(req, json.dumps(self.data))
...
/usr/local/lib/python2.7/json/__init__.py in dumps
return _default_encoder.encode(obj)
...
/usr/local/lib/python2.7/json/encoder.py in encode
chunks = self.iterencode(o, _one_shot=True)
...
/usr/local/lib/python2.7/json/encoder.py in iterencode
return _iterencode(o, 0)
...
/usr/local/lib/python2.7/json/encoder.py in default
raise TypeError(repr(o) + " is not JSON serializable")
...
Any ideas ?
Thanks,
Try this using urllib
import urllib
...
self.data = { example : "12345", 'Content-type':'application/json' }
self.data = urllib.urlencode(self.data)
req = urllib2.Request(api_url, self.data)
response = urllib2.urlopen(req)