Query on dictionary in python [duplicate] - python

This question already has answers here:
Why can't Python parse this JSON data? [closed]
(3 answers)
Closed 4 years ago.
[{"sku":43900,"name":"Batteries (4-Pack)","type":"HardGood","category": [{"id":"pc5","name":"Housewares"}]]
this is in json file.
i want to load this and make a dictionary in Python from this input.i tired to load but confused how to create dictionary from this input.
import json
data = []
json_file=open ('prod.json')
json_str=json_file.read()
json_data=json.loads(json_str)
for items in json_data:
print(items['name'])

import json
s = '[{"sku":43900,"name":"Batteries (4-Pack)","type":"HardGood","category": [{"id":"pc5","name":"Housewares"}]}]'
list_of_dicts = json.loads(s)
Your json was invalid; I added a } in the right place.

Related

How to make a list of JSON objects into a JSON file in Python and join multiple ones? [duplicate]

This question already has answers here:
What is the difference between Python's list methods append and extend?
(20 answers)
How do I write JSON data to a file?
(16 answers)
Closed 4 days ago.
The community reviewed whether to reopen this question 4 days ago and left it closed:
Original close reason(s) were not resolved
I am working with an API that returns the following format:
{
"count": 900,
"next": "api/?data&page=2",
"previous": null,
"results":
[{json object 1}, {json object 2}, {...}]
}
Problem is that I want to retrieve all "results" from all pages, and save that into one json file.
I'm thinking of a while loop that keeps making requests to the API and aggregating the resulting "results" into one variable, until the "next" value is null.
Something like
while json1["next"] != null:
r = request.get(apiURL, verify=False, allow_redirects=True, headers=headers, timeout=10)
raw_data = r.json()["results"]
final_data.update(raw_data)
I tried it but since r.json()["results"] is a list I don't know how to handle the different formats and transform that into a JSON file
When trying to do final_data.update(raw_data) it gives me an error saying:
'list' object has no attribute 'update'
Or when trying json.loads(raw_data) it gives me:
TypeError: the JSON object must be str, bytes, or bytearray, not list"
JSON file is a text file. To save your raw_data, which is a list, in a text file, you need to encode it using json.dumps():
import json
with open('output.json', 'w', encoding="utf-8") as f:
raw_data_as_string = json.dumps(raw_data)
f.write(raw_data_as_string)
To aggregate the results from different pages, your final_data can be a list, created before you iterate the pages, and then you can final_data.extend(raw_data) in a loop, where raw_data contains results from a single page.
After that you json.dumps(final_data) as shown earlier.

Python - Requests module "response.text" [duplicate]

This question already has an answer here:
How to extract values from a Python request
(1 answer)
Closed 6 months ago.
How do I get a specific element from requests response.text
{"status":"success","data":{"id":30815925}}
im need to get ID from that output
You can import the json package and simply do
import json
id = json.loads(response.text)["data"]["id"]
This will convert response.text from a string to a python dictionary, and the id will be inside the variable id

How can I access dict value in Flask config file for using in Jquery? [duplicate]

This question already has answers here:
How to access flask config in javascript?
(2 answers)
JavaScript raises SyntaxError with data rendered in Jinja template
(3 answers)
Closed 8 months ago.
I want to show the value when the key is mapping in Jquery.
I typed ACTION_STATES value in config.py Flask as dict type.
[Saved in DB]
[config.py]
ACTION_STATES = {
'Active': 'Go to the Next step',
'Completed': 'All process is finished'
}
I tried to use config value like below. Then the result is not what I want to do.
[Accessing in Jquery]
action_states = '{{config.ACTION_STATES}}'
console.log(action_states)
action_states = '{{config.ACTION_STATES.items()}}'
console.log(action_states)
How can I get the value in config.py using Jquery?
Is it possible to access?

How to read a specific value from within a JSON file? [duplicate]

This question already has answers here:
Nested dictionary value from key path
(9 answers)
Closed 1 year ago.
I want to know how to read a specific objects value from within a JSON object.
"worker_01": {
"data": {
"name": "Juan",
"manager": 0,
"weight": 75,
"positions": {
"FOH": 1,
"MOH": 1,
"BOH": 1
}
}
},
I know previously in Node.js I could read them by doing *.get(worker_01.data.name)*
but python doesn't really allow that. I want to know how do I do something similar to that in python.
Here is my source code.
import json as js
data_json = open('hello.json')
data_worker = js.load(data_json)
for i in data_worker['worker_01']:
print(i)
In Python, you can read JSON as a big python dictionary with mini listed dictionaries in between them all. With that in mind, you can index specific attributes from the JSON. For example based on your JSON, if a user wanted to get data on a persons name, you would do data_worker['worker_01']['data']['name'] to get the output 'Juan'
Here is more resources for you to look at too!
https://www.w3schools.com/python/python_json.asp
https://www.codegrepper.com/code-examples/python/how+to+get+specific+data+from+json+using+python
https://www.w3schools.com/python/python_dictionaries.asp

How can I parse JSON API using Python [duplicate]

This question already has answers here:
HTTP requests and JSON parsing in Python [duplicate]
(8 answers)
Closed 3 years ago.
I have a REST Api that only renders this data
data: "xxxxxxxxxxxxxxx"
I need to store this XXXXXXXXXX value in some variable using python, but I could only code and reach to the part where I get this value data:"xxxxxxxxxxxxxx"
my code is as follows
r = requests.get('url', headers=headers, verify=False)
logger.info(r)
which gives the output data: "xxxxxxxxxxxxxxx"
How can i fetch only XXXXXXXXXXXX from this json output ?
As simple as this could work for you.
r = requests.get('url', headers=headers, verify=False).json()
print(r['data'])

Categories

Resources