Add a key that contains a list in json - python

I need to add a key to a json. I have the following json on a variable:
[{"id":00000,"alert":"testing"}]
But I need the json object look like this:
{'keyA':[{"id":00000,"alert":"testing"}]}
How can I concatenate this key to the list?
Thx!

Just add the first object to a new dictionary like this:
jsonobj = [{"id":00000,"alert":"testing"}]
result = {'keyA':jsonobj}
and then you can either work with this dictionary or get the json value of it like:
import json
json.dumps(result)
And if you get only the json version of the input you have to use something like:
jsonobj = json.loads('[{"alert": "testing", "id": 0}]')
result = {'keyA':jsonobj}
json.dumps(result)

Related

I can't get a value from a JSON API response in python

So I am struggling with getting a value from a JSON response. Looking in other post I have managed to write this code but when I try to search for the key (character_id) that I want in the dictionary python says that the key doesn't exist. My solution consists in getting the JSON object from the response, converting it into a string with json.dumps() and the converting it into a dictionary with json.loads(). Then I try to get 'character_id' from the dictionary but it doesn't exist. I am guessing it is related with the format of the dictionary but I have little to none experience in python. The code that makes the query and tries to get the values is this: (dataRequest is a fuction that makes the request and return the response from the api)
characterName = sys.argv[1];
response = dataRequest('http://census.daybreakgames.com/s:888/get/ps2:v2/character/?name.first_lower=' + characterName + '&c:show=character_id')
jsonString = json.dumps(response.json())
print(jsonString)
dic = json.loads(jsonString)
print(dic)
if 'character_id' in dic:
print(dic['character_id'])
The output of the code is:
{"character_list": [{"character_id": "5428662532301799649"}], "returned": 1}
{'character_list': [{'character_id': '5428662532301799649'}], 'returned': 1}
Welcome #Prieto! From what I can see, you probably don't need to serialize/de-serialize the JSON -- response.json() returns a python dictionary object already.
The issue is that you are looking for the 'character_id' key at the top-level of the dictionary, when it seems to be embedded inside another dictionary, that is inside a list. Try something like this:
#...omitted code
for char_obj in dic["character_list"]:
if "character_id" in char_obj:
print(char_obj["character_id"])
if your dic is like {"character_list": [{"character_id": "5428662532301799649"}], "returned": 1}
you get the value of character_id by
print(dic['character_list'][0][character_id])
The problem here is that you're trying to access a dictionary where the key is actually character_list.
What you need to do is to access the character_list value and iterate over or filter the character_id you want.
Like this:
print(jsonString)
dic = json.loads(jsonString)
print(dic)
character_information = dic['character_list'][0] # we access the character list and assume it is the first value
print(character_information["character_id"]) # this is your character id
The way I see it, the only hiccup with the code is this :
if 'character_id' in dic:
print(dic['character_id'])
The problem is that, the JSON file actually consists of actually 2 dictionaries , first is the main one, which has two keys, character_list and returned. There is a second sub-dictionary inside the array, which is the value for the key character_list.
So, what your code should actually look like is something like this:
for i in dic["character_list"]:
print(i["character_id"])
On a side-note, it will help to look at JSON file in this way :
{
"character_list": [
{
"character_id": "5428662532301799649"
}
],
"returned": 1
}
,where, elements enclosed in curly-brackets'{}' imply they are in a dictionary, whereas elements enclosed in curly-brackets'[]' imply they are in a list

txt with str of dict into dict [duplicate]

I am trying to pass in a JSON file and convert the data into a dictionary.
So far, this is what I have done:
import json
json1_file = open('json1')
json1_str = json1_file.read()
json1_data = json.loads(json1_str)
I'm expecting json1_data to be a dict type but it actually comes out as a list type when I check it with type(json1_data).
What am I missing? I need this to be a dictionary so I can access one of the keys.
Your JSON is an array with a single object inside, so when you read it in you get a list with a dictionary inside. You can access your dictionary by accessing item 0 in the list, as shown below:
json1_data = json.loads(json1_str)[0]
Now you can access the data stored in datapoints just as you were expecting:
datapoints = json1_data['datapoints']
I have one more question if anyone can bite: I am trying to take the average of the first elements in these datapoints(i.e. datapoints[0][0]). Just to list them, I tried doing datapoints[0:5][0] but all I get is the first datapoint with both elements as opposed to wanting to get the first 5 datapoints containing only the first element. Is there a way to do this?
datapoints[0:5][0] doesn't do what you're expecting. datapoints[0:5] returns a new list slice containing just the first 5 elements, and then adding [0] on the end of it will take just the first element from that resulting list slice. What you need to use to get the result you want is a list comprehension:
[p[0] for p in datapoints[0:5]]
Here's a simple way to calculate the mean:
sum(p[0] for p in datapoints[0:5])/5. # Result is 35.8
If you're willing to install NumPy, then it's even easier:
import numpy
json1_file = open('json1')
json1_str = json1_file.read()
json1_data = json.loads(json1_str)[0]
datapoints = numpy.array(json1_data['datapoints'])
avg = datapoints[0:5,0].mean()
# avg is now 35.8
Using the , operator with the slicing syntax for NumPy's arrays has the behavior you were originally expecting with the list slices.
Here is a simple snippet that read's in a json text file from a dictionary. Note that your json file must follow the json standard, so it has to have " double quotes rather then ' single quotes.
Your JSON dump.txt File:
{"test":"1", "test2":123}
Python Script:
import json
with open('/your/path/to/a/dict/dump.txt') as handle:
dictdump = json.loads(handle.read())
You can use the following:
import json
with open('<yourFile>.json', 'r') as JSON:
json_dict = json.load(JSON)
# Now you can use it like dictionary
# For example:
print(json_dict["username"])
The best way to Load JSON Data into Dictionary is You can user the inbuilt json loader.
Below is the sample snippet that can be used.
import json
f = open("data.json")
data = json.load(f))
f.close()
type(data)
print(data[<keyFromTheJsonFile>])
I am working with a Python code for a REST API, so this is for those who are working on similar projects.
I extract data from an URL using a POST request and the raw output is JSON. For some reason the output is already a dictionary, not a list, and I'm able to refer to the nested dictionary keys right away, like this:
datapoint_1 = json1_data['datapoints']['datapoint_1']
where datapoint_1 is inside the datapoints dictionary.
pass the data using javascript ajax from get methods
**//javascript function
function addnewcustomer(){
//This function run when button click
//get the value from input box using getElementById
var new_cust_name = document.getElementById("new_customer").value;
var new_cust_cont = document.getElementById("new_contact_number").value;
var new_cust_email = document.getElementById("new_email").value;
var new_cust_gender = document.getElementById("new_gender").value;
var new_cust_cityname = document.getElementById("new_cityname").value;
var new_cust_pincode = document.getElementById("new_pincode").value;
var new_cust_state = document.getElementById("new_state").value;
var new_cust_contry = document.getElementById("new_contry").value;
//create json or if we know python that is call dictionary.
var data = {"cust_name":new_cust_name, "cust_cont":new_cust_cont, "cust_email":new_cust_email, "cust_gender":new_cust_gender, "cust_cityname":new_cust_cityname, "cust_pincode":new_cust_pincode, "cust_state":new_cust_state, "cust_contry":new_cust_contry};
//apply stringfy method on json
data = JSON.stringify(data);
//insert data into database using javascript ajax
var send_data = new XMLHttpRequest();
send_data.open("GET", "http://localhost:8000/invoice_system/addnewcustomer/?customerinfo="+data,true);
send_data.send();
send_data.onreadystatechange = function(){
if(send_data.readyState==4 && send_data.status==200){
alert(send_data.responseText);
}
}
}
django views
def addNewCustomer(request):
#if method is get then condition is true and controller check the further line
if request.method == "GET":
#this line catch the json from the javascript ajax.
cust_info = request.GET.get("customerinfo")
#fill the value in variable which is coming from ajax.
#it is a json so first we will get the value from using json.loads method.
#cust_name is a key which is pass by javascript json.
#as we know json is a key value pair. the cust_name is a key which pass by javascript json
cust_name = json.loads(cust_info)['cust_name']
cust_cont = json.loads(cust_info)['cust_cont']
cust_email = json.loads(cust_info)['cust_email']
cust_gender = json.loads(cust_info)['cust_gender']
cust_cityname = json.loads(cust_info)['cust_cityname']
cust_pincode = json.loads(cust_info)['cust_pincode']
cust_state = json.loads(cust_info)['cust_state']
cust_contry = json.loads(cust_info)['cust_contry']
#it print the value of cust_name variable on server
print(cust_name)
print(cust_cont)
print(cust_email)
print(cust_gender)
print(cust_cityname)
print(cust_pincode)
print(cust_state)
print(cust_contry)
return HttpResponse("Yes I am reach here.")**

Extend JSON files with Python

I looked my problem up on stackoverflow and there are several solutions to my problem which just don't work in my case.
I want to add a few new entries to my json file.
My json file (data.json):
{
"blabla1":"dubdub1",
"blabla2":"dubdub2"
}
My code (using the extend method):
import json
with open('data.json') as json_data_file:
data = json.load(json_data_file)
result = list()
result.extend(data)
result.extend({'blabla3': 'dubdub3'})
data = result
print(data)
Which gives me an output like:
['blabla1', 'blabla2', 'blabla3']
My code (using the append method):
import json
with open('data.json') as json_data_file:
data = json.load(json_data_file)
result = list()
result.append(data)
result.append({'blabla3': 'dubdub3'})
data = result
print(data)
Which gives me an output like:
[{'blabla1': 'dubdub1', 'blabla2': 'dubdub2'}, {'blabla3': 'dubdub3'}]
What I need in the end is this:
[{'blabla1': 'dubdub1', 'blabla2': 'dubdub2', 'blabla3': 'dubdub3'}]
So where am I going wrong? I'm sorry if the same question has already been answered, but I couldn't find something that worked for me. Thank you!
Without changing your code much you could achieve your original request like this:
import json
with open('data.json') as json_data_file:
data = json.load(json_data_file)
data.update({'blabla3': 'dubdub3'})
result = [data]
print(result)
Which will produce your expected result:
[{'blabla1': 'dubdub1', 'blabla2': 'dubdub2', 'blabla3': 'dubdub3'}]
Short explanation:
The method json.load you called created a dictionary object data that looks like this:
{'blabla1': 'dubdub1', 'blabla2': 'dubdub2'}
Then by calling result.append(data) you added the data dictionary as the first citizen in the list object result:
[{'blabla1': 'dubdub1', 'blabla2': 'dubdub2'}]
And every other time you call the append() method you will just add another member to the list:
[{'blabla1': 'dubdub1', 'blabla2': 'dubdub2'}, obj2, obj3, ...]
Instead it seems you wanted to add another key-value pair to the data dictionary as explained in the previous answer
Is this closer to what you want? A dictionary updated with the new key and value
import json
with open('data.json') as json_data_file:
data = json.load(json_data_file)
data['blabla3'] = 'dubdub3'
print(data) # {'blabla1': 'dubdub1', 'blabla2': 'dubdub2', 'blabla3': 'dubdub3'}
EDIT:
To update multiple entries at the same time you can use update
data.update({
'blabla3': 'dubdub3',
'blabla4': 'dubdub4',
})

Remove 'u' in JSON dictionary

I hope to use the dictionary load by json file. However, each item contains the character 'u'. I need to remove the 'u's.
I tried dumps, but it does not work.
import ast
import json
data= {u'dot',
u'dog',
u'fog',
u'eeee'}
res = eval(json.dumps(data))
print res
I hope to get: {
'dot',
'dog',
'fog,
'eeee'
}
But the error is:
TypeError: set([u'eeee', u'fog', u'dog', u'dot']) is not JSON serializable
The strings that start with u are unicode strings.
In your case, this has nothing to do with the problem:
data= {u'dot',
u'dog',
u'fog',
u'eeee'}
This creates a set and stores the results in the data variable. The json serializer can't handle sets since the json spec makes no mention of them. If you change this to be a list, the serializer can handle the data:
res = set(eval(json.dumps(list(data))))
Here I'm converting the data variable to a list to serialize it, then converting it back to a set to store the result in the res variable.
Alternatively, you can directly ask Python to convert the unicode strings to strings, using something like this:
res = {x.encode("utf-8") for x in data}
print(res)

How to put pickle dict value into an object

I am using pickle to dump a dictionary object into a txt file. I need to grab the dictionary from the file and extract only certain values and put them inside of an object as a string.
My dictionary looks something like this:
obj_dict = { 'name': 'MYID', 'value': 'usdf23444',
'name': 'MYID2', 'value' : 'asdfh3479' }
Part of the dilemma I have is that there are two 'name' and two 'value' in the dictionary and I need to grab each separately.
Here is the code I am using:
import pickle
filepath = file.txt
output = open(filepath, 'rb')
obj_dict = pickle.load(output)
for i in obj_dict:
NewString = "VALUE1=" + i['value1'] + "VALUE2=" + i['value2']
print(NewString)
I know this code doesn't work, I'm more showing what I need my end result to look like but basically I need each value to be put into a string that I can use later. How can I reference 'value1' and 'value2' correctly? Also I am getting this error when trying to just get one 'value':
TypeError: list indices must be integers or slices, not str
EDIT FOR COMMENT 2
I'm not sure if that's true, I can run this code:
output = open(filepath, 'rb')
obj_dict = pickle.load(output)
for i in obj_dict:
print(i['value'])
and my output is:
usdf23444
asdfh3479
After the update, it looks like it is a list of dicts. Try:
strings = ["VALUE{}={}".format(i, d['value']) for i, d in enumerate(obj_dict)]

Categories