dct_data = json_tour_data.__dict__
tour_data = json.dumps(dct_data)
How to remove these backslashes from json? Here is my output:
"{\"strFileOpenDateAjxKey\": \"2018-01-16 12:40:22.526417\",
\"strFilePassengerAjxKey\": \"Zahra Walji\", \"strFileOpenMobileAjxKey\":
\"46464664\", \"strFileOpenDepartmentAjxKey\": \"Finance department\",
\"strFileOpenAccountCodeAjxKey\": \"CARTZS\",
\"strFileOpenProfileCodeAjxKey\": \"CARTZS\",
\"strFileopenOriginalCountryIdAjxKey\": 61, \"blnBoundAjxKey\": 1,
\"strTransactionCurrencyJsKey\": \"Shillings\",
\"intCurrencyPrecisionJsKey\": 3, \"strPackageTypeJsKey\": \"PKG\",
\"strUserNameAjxKey\": \"admin\", \"strPasswordAjxKey\": \"1234\"}"
The answer is you have to just play with json.dumps() and json.loads().
The following is my code which worked:-
import json
json_data = {'key1': 'first'}
json_data = json.dumps(json_data)
return {
'statusCode': 200,
'schools': json.loads(json_data)
}
The output of above code is as follows:
Response:
{
"schools": {
"key1": "first"
},
"statusCode": 200
}
I would recommend checking your Response object where your parse your tour_data variable/dictionary in your views. I originally had the same issue as you but here's what I changed.
Original implementation: Response(json.dumps(a_dictionary), status=status.HTTP_200_OK)
to
New implementation: Response(a_dictionary, status=status.HTTP_200_OK, content_type='json')
The key things here are:
1. Getting rid of the json.dumps conversion method and just pass through a plain python dictionary e.g. see a_dictionary.
2. Setting content_type='json' on the Response object.
you can use replace("\'", '"') for that.
json = '''{\"strFileOpenDateAjxKey\": \"2018-01-16 12:40:22.526417\",
\"strFilePassengerAjxKey\": \"Zahra Walji\", \"strFileOpenMobileAjxKey\":
\"46464664\", \"strFileOpenDepartmentAjxKey\": \"Finance department\",
\"strFileOpenAccountCodeAjxKey\": \"CARTZS\",
\"strFileOpenProfileCodeAjxKey\": \"CARTZS\",
\"strFileopenOriginalCountryIdAjxKey\": 61, \"blnBoundAjxKey\": 1,
\"strTransactionCurrencyJsKey\": \"Shillings\",
\"intCurrencyPrecisionJsKey\": 3, \"strPackageTypeJsKey\": \"PKG\",
\"strUserNameAjxKey\": \"admin\", \"strPasswordAjxKey\": \"1234\"}'''
newString = json.replace("\'", '"')
print(newString)
check from here
that is the output when pressed the run in my side.
To anyone else who might be facing this issue.
simply put:
the original question seems to be taking JSON data (I emphasize, it's already JSON) and rendering it into JSON again.
dct_data = json_tour_data.dict
tour_data = json.dumps(dct_data)
Related
I'm getting below output from an API and I want to read all purchaseOrder data. Not really sure how to loop on this data. Also it comes with b' at the front.
b'[
{"purchaseOrder":
[
{
"id":"d01f0f6d-398f-4220-8a9a-44f47beedf04",
"installationNumber":null,
"peerId":"308866ba-90cb-47a7-8c73-589c0f355eb7",
"validFrom":"2019-06-07T12:51:15.000+0000",
"validTo":"2019-06-07T13:51:15.000+0000",
"originalQuantity":5,
"quantity":5,
"price":5,
"periodInitial":"2019-06-07T13:00:00.000+0000",
"periodFinal":"2019-06-07T14:00:00.000+0000"
}
],
"salesOrder":null,
"agreement":null,
"status":""
}
]'
Have tried things like loaded_json = json.load(r.content) and it didn't work.
This is code I use to get the response:
r = requests.post(url=api_endpoint, data=json.dumps(json_post), headers=headers)
To get the json of a response use data = response.json().
After that you can step through it like normal lists and dicts:
import json
data = r.json()
print(json.dumps(data , indent=2)) # If you want to see the data from the response
for dic in data :
if 'purchaseOrder' in dic:
for item in dic['purchaseOrder']:
# item here is the `dict` for each purchaseOrder (PO).
print(json.dumps(item, indent=2)) # This will print each item in PO.
Thanks all for support. The next code works for me:
data = r.json()
print(json.dumps(data, indent=2))
for dic in data:
if 'purchaseOrder' in dic:
for itemdata in dic['purchaseOrder']:
for key in itemdata:
if key == 'id':
print("Id:")
print(itemdata['id'])
print("Price:")
print(itemdata['price'])
I have a big tree in a JSON file and I'm searching the python syntax for loading nested in nested keys from this JSON.
Assume I have this :
{
"FireWall": {
"eth0": {
"INPUT": {
"PING": 1,
}
}
}
}
According to the man page and some questions in Stackoverflow i tried this (and some variations) :
import json
config = open('config.json', 'r')
data = json.load('config')
config.close()
if data['{"FireWall", {"eth0", {"INPUT", {"Ping"}}}}'] == 1:
print('This is working')
With no result. What is the right way to do this (as simple as possible) ? Thank you !
You are trying data = json.load('config') to load string not file object and data['{"FireWall", {"eth0", {"INPUT", {"Ping"}}}}'] it's not right way to access nested dictionary key value.
import json
with open('config.json', 'r') as f:
data = json.load(f)
if data["FireWall"]["eth0"]["INPUT"]["Ping"] == 1:
print('This is working')
data is a nested dictionary, so:
data["FireWall"]["eth0"]["INPUT"]["Ping"]
will be equal to 1; or at least it will when you fix your call to json.load.
Try this:
data["FireWall"]["eth0"]["INPUT"]["PING"]
This will give you the value in PING
As a json response I got it from server
{"Data":["{\"item1\": \"value1\",\"item2\": \"value2\"}"]}
I used
a=json.loads(response)
print(a)
self.write(a)
From terminal I saw
{u'Data':[u'{"item1": "value1", "item2": "value2"}"]'}
From postman it's like
{"Data":["{\"item1\": \"value1\",\"item2\": \"value2\"}"]}
I need as
{"Data":[{"item1": "value1","item2": "value2"}]}
I know all this format are right but I prefer the last format in postman. Thanks in advance
I tried the below and it works...
content = json.loads(content)['data']
temp = []
for values in content:
jstr = json.loads(values)
temp.append(jstr)
val = {"data": temp}
self.write(json.dumps(val))
I'm trying to work with dictionaries inside a list in a JSON file. The data imports fine and reads fine. For the life of me I can't figure out how to printout the "member_id" keys. I just want to print the list of "member_id" numbers. I was initially using json.loads, then switched to json.dumps. Any help would really be appreciated.
import urllib2
import json
nyt_api_key = '72c9a68bbc504e91a3919efda17ae621%3A7%3A70586819'
url= 'http://api.nytimes.com/svc/politics/v3/us/legislative/congress/113'
json_obj = urllib2.urlopen(url)
data = json.load(json_obj)
data2 = json.dumps(data, sort_keys=True, indent=True, skipkeys = True)
print data2
Output from print data2: (The list goes on and on so it is truncated. There is a closing bracket at the bottom of the list. So it's dictionaries within a list.)
"positions": [
{
"dw_nominate": "0.466",
"member_id": "A000055",
"vote_position": "Yes"
},
{
"dw_nominate": "0.995",
"member_id": "A000367",
"vote_position": "Yes"
},
{
"dw_nominate": "0.666",
"member_id": "A000369",
"vote_position": "Yes"
},
Output from print data2['member_id'], output is the same if using 'positions', 'vote_position', etc.:
Traceback (most recent call last):
File "/Users/Owner/PycharmProjects/untitled2/1", line 9, in <module>
print data2["positions"]
TypeError: string indices must be integers, not str
Output from print data:
u'positions': [{u'dw_nominate': u'0.466', u'vote_position': u'Yes', u'member_id': u'A000055'}, {u'dw_nominate': u'0.995', u'vote_position': u'Yes', u'member_id': u'A000367'}, {u'dw_nominate': u'0.666', u'vote_position': u'Yes', u'member_id': u'A000369'}
Output from print data['positions']:
print data["positions"]
KeyError: 'positions'
Output from print.data(keys):
[u'status', u'results', u'copyright']
Process finished with exit code 0
I just want to print the list of "member_id" numbers.
So you need to loop over positions and access the member_id in each dict:
data ={"positions": [
{
"dw_nominate": "0.466",
"member_id": "A000055",
"vote_position": "Yes"
},
{
"dw_nominate": "0.995",
"member_id": "A000367",
"vote_position": "Yes"
},
{
"dw_nominate": "0.666",
"member_id": "A000369",
"vote_position": "Yes"
}]}
print([d["member_id"] for d in data["results"]["positions"]])
['A000055', 'A000367', 'A000369']
If you look at the API documentation there are examples of each json response.
data2 is a string value, it doesn't have keys. I think what you want to print is data["positions"]
That's a weird output from data, you don't even have the braces. Try printing the type(data), it should be dict
So I should change the heading of this to Scrapping JSON for XML in Python. I'm sure not everyone else would have the same issues I did with JSON but after many frustrating hours I decided to go down path #2... the xml version. The xml version was much easier to work with right out of the gate. In about 1/10 the time I got what I was looking for.
from urllib2 import urlopen
from xml.dom import minidom
feed = urlopen("http://api.nytimes.com/svc/politics/v3/us/legislative.xml?
doc = minidom.parse(feed)
id_element = doc.getElementsByTagName("member_id")
id_number0 = id_element[0].childNodes[0].nodeValue #just a sample
id_number1 = id_element[1].childNodes[0].nodeValue #just a sample
id_number2 = id_element[2].childNodes[0].nodeValue #just a sample
print len(id_element) #to see how many items were in the variable
count = 0
for item in id_element:
print id_element[count].childNodes[0].nodeValue
count = count + 1
if count == 434:
break
This is definitely not the cleanest loop. I'm still working on that. But the code solves the problem that I had originally posted. The API key is not the actual one, formatting in the answer window was throwing it off so I just erased a bunch of it. You can find the API at the NYT developer website.
Thanks to everyone who posted.
I have a list of python dictionaries that look like this:
sandwiches = [
{'bread':'wheat', 'topping':'tomatoes', 'meat':'bacon'},
{'bread':'white', 'topping':'peanut butter', 'meat':'bacon'},
{'bread':'sourdough', 'topping':'cheese', 'meat':'bacon'}
]
I want to pass this as a POST parameter to another Django app. What does the client app need to do to iterate through the list?
I want to do something like:
for sandwich in request.POST['sandwiches']:
print "%s on %s with %s is yummy!" % (sandwich['meat'], sandwich['bread'], sandwich['topping'])
But I don't seem to have a list of dicts when my data arrives at my client app.
You don't say how you're POSTing to the app. My advice would be to serialize the dictionaries as JSON, then simply POST that.
import json, urllib, urllib2
data = json.dumps(sandwiches)
urllib2.urlopen(myurl, urllib.urlencode({'data': data}))
... and on the receiver:
data = request.POST['data']
sandwiches = json.loads(data)
I would use the JSON libraries to serialize your array of dicts into a single string. Send this string as a POST param, and parse the string back into the python datatypes in the Django app using the same library.
http://docs.python.org/library/json.html
firstly make string of the list
import ast, requests
# request send code
dev_list = [{"1": 2}, {"2": 4}]
str_list = str(dev_list) # '[{"1": 2}, {"2": 4}]'
data = {"a" : "mynema",
'str_list': str_list
}
requests.post(url, data )
#request receive side
data = request.data
dev_list = data.get('str_list')
dev_list = ast.literal_eval(dev_list)
#dev_list --> [{"1": 2}, {"2": 4}]
Now you receive list of dictionary.