how to get a data from another data in python json - python

This is the response I get from the server:
[{"status": "OK", "data":[{"Number":"9358925074","Name":"mark","Family":"tomson"}]}]
and if I want to get the Name value from the response, what can I do? can someone make a example in python?

You can do this.
>>> data = [{"status": "OK", "data":[{"Number":"9358925074","Name":"mark","Family":"tomson"}]}]
>>> data[0]['data'][0]['Name']
'mark'
output:
'mark'

This worked for me:
data = json.loads(j.content.decode())
for d in data:
pass
name = (d['data'][0]['Number'])
print(name)
output:
9358925074

Related

How to filter out data from a print out message

I have this one problem, where I print out a message response from a website(JSON response), and the response I get is this.
Here is my model with fake data:
{"token": "MTAxOTAwNjM4NjEyMzg0OTkwMQ.8hkyLV.n0ir2UA4qFE5pXen9YnPtFzgn4xP8tHmVmmkrl", "user_settings": {"locale": "en-US", "theme": "dark"}, "user_id": "101900638614857883"}
And, if I only want the value of "token" data which are this (MTAxOTAwNjM4NjEyMzg0OTkwMQ.8hkyLV.n0ir2UA4qFE5pXen9YnPtFzgn4xP8tHmVmmkrl) and I want to store it into a txt file, is there any good way to do it?
Thank you, guys!
I tried print(r.text('token')) but it did not work, since it only works on printing the category of the data's (like : Category : {"token" : 'daefafa', "user-id" : 'er121231231', more})
In python, JSON is treated as a dictionary.
To filter it use dictionary comprehension
tokenData = {key: val for key,val in data_json.items() if key == 'token'}
Full Code Snippet :
from urllib.request import urlopen
import json
url = "enter-your-url"
response = urlopen(url)
data_json = json.loads(response.read())
print(type(data_json)) # <class 'dict'>
#use dict comprehension
jsonToken = {key: val for key,val in data_json.items() if key == 'result'}
strToken = json.dumps(jsonToken)
# Only string json can be written to files
with open('data.txt','w') as file:
file.write(strToken)
file.close()
You need to parse the JSON into a dictionary using json.loads(). Like this:
import json
# ...
# request-getting code
# ...
data = json.loads(r.text)
print(data['token'])

Python format json output

I have output from json as below from curl:
{'TableViewConfig': {'displayLength': 50, 'Resources': ...}}
it needs to be passed in another curl get command with data but in below format:
{\"TableViewConfig\":{\"displayLength\":50,\"Resources\":...}}
Can you please help in resolving the str replace in python dict?
Tried below, but it didnt work:
request = 'url'
response = requests.get(request)
data = json.loads(response)
print(data)
orig = list(map(lambda item: dict((k.replace(''', ''\'), v.replace(''', ''\')) for k, v in item.items()), data))

Reading JSon return values from an API

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

Backslash is added to JSON before double quote

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))

How to extract value with simplejson?

I have the following json string:
{"response":[[{"uid":123456,"name":"LA_"}],[{"cid":"1","name":"Something"}],[{"cid":1,"name":"Something-else"}]]}
How can I get Something value?
I do the following
jstr = json.loads(my_string)
if jstr.get('response'):
jstr_response = jstr.get('response')[1].get('name')
but it doesn't work ('list' object has no attribute 'get')
Try this.
jstr = json.loads(my_string)
if jstr.get('response'):
jstr_response = jstr.get('response')[1][0].get('name')

Categories