I am using django rest framework to returned response in json format for jquery.
I have a dictionary object which contains another dictionary object:
items = {
['name':'Chairs','options':{'type':'office','price':100}],
['name':'Tables','options':{'type':'office','price':45}],
}
response = Response( json.dumps(output_items) , status=status.HTTP_200_OK)
On JavaScript side I am using this code:
var array = JSON.parse(json);
that is not parsing JSON, that is creating errors.
I want to create this json format:
{
"1": {
"name": "Chairs",
"description": "All chairs",
"options": {
"1":{"type": "Office", "price": 130 },
"2":{"type": "Home", "price": 75 },
"3":{"type": "Shop", "price": 100 }
}
},
"2": {
"name": "Tables",
"description": "table description",
"options": {
"1":{"type": "Office", "price": 240 },
"2":{"type": "Home", "price": 200 },
"3":{"type": "Shop", "price": 180 }
}
}
}
I stored all my data using python dictionary and list objects , how can i create this format json output string from dictionaries data?
This is not a proper json or Python object. Python Lists cannot take named arguments. Only a dictionary can take key, value pairs. If you wish to go for a list, it has to be dictionaries added to the list and not as key value pairs. The items should be something like this:
List of dictionaries
items = [
{"name":"Chairs","options":{"type":"office","price":100}},
{"name":"Tables","options":{"type":"office","price":45}},
]
(or)
Dictionary of dictionaries
items = {
"first":{"name":"Chairs","options":{"type":"office","price":100}},
"second":{"name":"Tables","options":{"type":"office","price":45}}
}
You have an error in you object "items". Try this one
items = [
{'name':'Chairs','options':{'type':'office','price':100}},
{'name':'Tables','options':{'type':'office','price':45}},
]
You have an error in dict creation ['name':'Chairs','options':{'type':'office','price':100}] This is not a pair of key: value
you are not doing it correctly as mentioned by others, you can test it in your browser's console just type in
x={'type':'office','price':100}
//Object {type: "office", price: 100}
y={'type':'office','price':45}
//Object {type: "office", price: 45}
opt1={'type':x}
//Object {type: Object}
opt2={'type':y}
//Object {type: Object}
val1={'name':'Chairs', 'options':opt1}
//Object {name: "Chairs", options: Object}
val2={name:'tables','options':opt2}
//Object {name: "tables", options: Object}
items={'1':val1,'2':val2}
you will have the needed format for your data and you will get an idea about how to formulate the data too. hope it helps
Related
I'm trying to search a JSON Object and extract the Key/Value pairs for 'name' and 'id' below. I would like to extract all instances of the 'name' and 'id':
{
"response": [
{
"additionalInfo": [],
"id": "b6549916-b8e1-4131-b0be-f4a3daee26fc",
"instanceTenantId": "5ffc97db91d68700c7ea827a",
"name": "Global",
"siteHierarchy": "b6549916-a8e1-4131-b0be-f4a3daee26fc",
"siteNameHierarchy": "Global"
},
{
"additionalInfo": [
{
"attributes": {
"addressInheritedFrom": "66284774-4ae4-42a1-b27c-68231c98d7db",
"type": "area"
},
"nameSpace": "Location"
}
],
"id": "4ffb292c-4cc8-444b-8978-61b97c6874db",
"instanceTenantId": "5ffc97db91d68700c7ea827a",
"name": "Peak Tester",
"parentId": "66a84774-4ae4-42a1-b27c-68231c98d7db",
"siteHierarchy": "b6549916-b8e1-4131-b0be-f4a3daee21fc/66a84774-4ae4-42a1-b27c-68231c98d7db/4ffb292c-4cc8-444b-8978-61b97c6874db",
"siteNameHierarchy": "Global/Template Site/Peak Tester"
}
]
}
I have tried several things that are not working.
for elements in site_info['response']:
for item in elements:
if item == 'name':
print(item)
This only prints the output of 'name' and not the value. I would like the value as well as the key.
Simply when you have the key and you need the value, you have to do this:
>>> dictionary['key']
'value'
In your case:
if item == 'name':
print(item['name'])
Anyway you can simply omitt the if statement this way:
for item in elements:
print(item['name'])
I see you already have your answer, which is great.
data = { "response": [ {"name" : "fred"}, {"name" : "tom"}]} # data is a dictionary
arr = data['response'] # arr is a list of dictionaries
for i in arr:
print('name', i['name']) # lookup the name value from each sub-dictionary
I'm working with a nested mongo backend and am in the process of mapping it to SQL database tables. A user can fill in forms which will be stored as following
{
"response": {
"question_1": "answer_1",
"question_2": [
"answer_a",
"answer_b"
]
},
"user": "user_1",
"form_id": "2344"
}
Questions can have multiple answers stored as an array.
I would like to flatten this into a long format (Ie a single record per question-answer combination) like so
[
{
"question_id": "question_1",
"answer": "answer_1",
"user": "user_1",
"form_id": "2344"
},
{
"question_id": "question_2",
"answer": "answer_a",
"user": "user_1",
"form_id": "2344"
},
{
"question_id": "question_2",
"answer": "answer_b",
"user": "user_1",
"form_id": "2344"
}
]
What would be the most efficient way to achieve this in python?
I could brute-force it by looping over every response in the response dict but I have the feeling that's overkill...
Many thanks
EDIT:
A first working attempt uses the following function:
def transform_responses_to_long(completed_form: Dict):
responses = completed_form["response"]
del completed_form["response"]
for key, values in responses.items():
if not isinstance(values, (List, Dict)):
values = [values]
for value in values:
result = {}
result.update(completed_form)
result.update({"question_id": key, "answer": value})
yield result
Which yields the correct dict for every question: answer combination
I have a simple json in python that looks like :
{
"list": [{
"key1": "value1"
},
{
"key1": "value1"
}
]
}
I want to transform this to the following json. Any suggestions how I can do it with python without installing additional libraries?
{
"list": [{
"keys": {
"name": "key1",
"value": "value1"
}
}, {
"keys": {
"name": "key1",
"value": "value1"
}
}]
}
Not sure from your question if you already have the json read into a variable, or if it is in a file. This is assuming you have it in a variable already:
in_json = {
"list": [{
"key1": "value1"
},
{
"key2": "value2"
}
]
}
out_json = {"list":[]}
for kd in in_json["list"]:
sub_kd = {"keys": {}}
for k,v in kd.iteritems():
sub_kd["keys"]["name"] = k
sub_kd["keys"]["value"] = v
out_json["list"].append(sub_kd)
print(out_json)
It just loops through the json making dictionaries to append to the out_json dictionary. You could make this print pretty with the json library and also save to file with it
You didn't indicate exactly what contains the JSON data is in, so I've put it all in a string in the example code below and uses the json.loads() function to turn it into a Python dictionary. If it's in a file, you can use the module's json.load() function instead.
It also make the assume that each sub-JSON object in the "list" list consists of only one key/value pair as shown in your question.
The code below changes the deserialized dictionary in-place and pretty-prints the result of doing that by using the json.dumps() function to reserialize it.
Note that I changed the keys and values in sample input JSON slightly to make it easier to see the correspondence between it and the printed results.
import json
json_in = '''
{
"list": [
{
"key1": "value1"
},
{
"key2": "value2"
}
]
}
'''
json_data = json.loads(json_in) # Deserialize.
for i, obj in enumerate(json_data['list']):
# Assumes each object in list contains only one key, value pair.
newobj = { 'name': next(iter(obj.keys())),
'value': next(iter(obj.values()))}
json_data['list'][i] = {'keys': newobj}
print(json.dumps(json_data, indent=4)) # Reserialize and print.
Printed result:
{
"list": [
{
"keys": {
"name": "key1",
"value": "value1"
}
},
{
"keys": {
"name": "key2",
"value": "value2"
}
}
]
}
The workplace api returns a json response:
{
"name": "AA",
"owner": {
"name": "ser1",
"id": "1234"
},
"id": "567",
"admins": {
"data": [
{
"name": "codez",
"id": "457"
},
],
"paging": {
"cursors": {
"before": "qwrqwreqreqr",
"after": "teyryryryr"
}
}
}
I access the json response in python using the below for loop:
for item in feed:
row = [item["name"],item["id"], item["email"], item["privacy"],item["updated_time"],item["admins"]["data"]["name"]]
I get the error "list indices must be integers or slices, not list". When I remove the item["admins"]["data"]["name"], I don't get the error message.
Any suggestions would be appreciated !!
You need to access list. The data node contains a list so you need to access index 0 then access the key value pair.
for item in feed:
row = [item["name"],item["id"], item["email"], item["privacy"],item["updated_time"],item["admins"]["data"][0]["name"]]
data maps to a list with size one so you could do item["admins"]["data"][0]["name"]
Although this could be done much easier with row = item.values()
I have been tasked with combining data from two different sources into one JSON to be used by a web service. I decided to go with flask which I have found to be so easy to use.
Anyway, I am retrieving JSON that looks like this ( via urlib2 )....
[
[{
"timestamp": 1474088400000,
"errors": 1018831,
"errorTotal": 72400021,
"errorTotal2": 0.013022892930509898,
"business": 4814994,
"breakdown": [{
"type": "type1",
"count": 603437
}, {
"type": "type2",
"count": 256187
}]
}]
]
All I am trying to do is add a new key pair under "breakdown", specifically "type3", so the JSON object looks like this...
[
[{
"timestamp": 1474088400000,
"errors": 1018831,
"errorTotal": 72400021,
"errorTotal2": 0.013022892930509898,
"business": 4814994,
"breakdown": [{
"type": "type1",
"count": 603437
}, {
"type": "type2",
"count": 256187
}, {
"type": "type3",
"count": 4533
}]
}]
]
I thought treating it like key pairs in a list would be the way to go but it doesn't seem to be working. Can anyone point me in the right direction ?
Many thanks in advance!
First, you should read the json into Python objects:
data = json.loads(jsonstring)
Then get to the object to be modified. The data looks like [ [ {... 'breakdown': ...} ] ], so it is a list of lists of dictionaries. I guess you want all of them:
for d in data:
for dd in d:
d['breakdown'].append({"type": "type3", "count": 4533})
Then convert it back to json:
update_json = json.dumps(data)
Load the json string
json_data = json.loads(json_string)
Iterate over the object and append to the "breakdown" key
for item in json_data:
for json_dict in item:
json_dict["breakdown"].append({"type": "type3", "count": 4533})
Convert it back to the JSON string
json_string = json.dumps(json_data)