How to store several values in JSON [duplicate] - python

This question already has answers here:
How to append to a JSON file in Python?
(3 answers)
Closed 3 years ago.
I have a Python project and need to store multiple values ​​in JSON, but only the first value is stored. I tried to use a loop structure but still only the first value is stored. How can I store all values?
The code:
entry = {
'face_names': "any",
'data_atual': data_texto
}
with open('consulte.json', 'w') as filehandle:
json.dump(entry, filehandle)

Can you provide input values? But if you want to bind plural values to one key, then you should create a list of values and add it into the dict.
face_names = [<some_values_inside>]
entry['face_names'] = face_names

Assuming you want to store your data_texto object to JSON.
So it's not possible if your object is not the type of let's say dict:
import json
data_texto = {
'1': "1",
'2': {'1': "2"}
}
entry = {
'face_names': "any",
'data_atual': data_texto
}
with open('consulte.json', 'w') as filehandle:
json.dump(entry, filehandle)
Will output as:
{"face_names": "any", "data_atual": {"1": "1", "2": {"1": "2"}}}

Related

How to append data to a sub-dictionary in a JSON file? [duplicate]

This question already has answers here:
Python - Appending JSON object to exisiting JSON object
(2 answers)
Closed last year.
I want to add some Python dictionary into a JSON file and append into a sub-dictionary
This is just a template of what my JSON file looks like:
{
"playerInfo": {
}
}
Let's say I want to access the key "playerInfo" and append data, specifically another dictionary, into this JSON file. This would be a dictionary that I would append to "playerInfo"
"player1":{
"name":"player1",
"id":1
}
The end result that I am looking for would be to have this
{
"playerInfo":{
"player1":{
"name":"player1",
"id":1
}
}
}
And for any future data, I would append it after the "player1" dictionary. How would I be able to accomplish this?
If you started with this:
x = {
"playerInfo": {
}
}
And wanted to add a player, do this:
x["playerInfo"]["player1"] = {
# Enter player data here
}
or
x["playerInfo"]["player1"] = {}
x["playerInfo"]["player1"]["name"] = "player1"
x["playerInfo"]["player1"]["id"] = i
To append more keys:
x["playerInfo"]["player1"]["<new key>"] = "<new value>"
And to add a new player
x["playerInfo"]["<new player>"]["<new key>"] = "<new value>"
This code only highlights the fact that a new player is created by adding a <new player> key to the playerInfo dictionary.

Spread array as dictionary key [duplicate]

This question already has answers here:
Access nested dictionary items via a list of keys?
(20 answers)
Use a dict to access nested instances of classes in Python
(3 answers)
How to convert string to class sub-attribute with Python
(3 answers)
Closed 4 years ago.
Consider the following dict:
{
"a" : {
"b" : [
entry,
entry,
...
]
}
}
Is there any way to address each entry given a key in the form "a.b"?
Ideally one could write something like dict[*("a.b".split("."))] and get dict["a"]["b"], but I have found no way to do it in Python yet.
Edit 2
Since no one seems to really care about quality code, I ended up using a plain old for loop:
data = { "a" : { "b" : "foo" } }
key = "a.b"
d = data
for k in key.split("."):
d = d[k]
d == data["a"]["b"] # True
Edit 3
Comments contain a valid solution:
import operator
from functools import reduce # forward compatibility for Python 3
data = { "a" : { "b" : "foo" } }
key = "a.b"
d = reduce(operator.getitem, key.split("."), data)
d == data["a"]["b"] # True
However, apart from this, I guess there is no way to exploit some language feature to do that, which kind of was the original question.

How to Combine two JSON files? [duplicate]

This question already has answers here:
How can I add new keys to a dictionary?
(19 answers)
Closed 5 years ago.
I've two json objects, I 'm figuring out a way on how to merge them in python
y={"success":"true"}
x={"0":"740","1":"747","2":"883","3":"750","4":"769"}
I need the final result in the following manner
{"success":"true",
"data":{
"0":"740",
"1":"747",
"2":"883",
"3":"750",
"4":"769"
}
}
I am trying to append it, but its showing some error. Help me with the code in python.
your input seem to be strings and not dictionaries. you need to convert them to dicts using json.loads:
import json
y = '{"success":"true"}'
x = '{"0":"740","1":"747","2":"883","3":"750","4":"769"}'
res = json.loads(y)
res['data'] = json.loads(x)
print(res)
if you need the output as string again, use json.dumps:
res_str = json.dumps(res)
if you insist on having the ouput sorted:
res_str = json.dumps(res, sort_keys=True)
You can simply do y["data"] = x
y={"success":"true"}
x={"0":"740","1":"747","2":"883","3":"750","4":"769"}
y["data"] = x
I assume that they are strings and not python dicts. So here is what you can do
y='{"success":"true"}'
x='{"0":"740","1":"747","2":"883","3":"750","4":"769"}'
import json
dict1 = json.loads(x)
dict2 = json.loads(y)
dict2['data'] = dict1
result = json.dumps(dict2)
print result
The code above gives you this
{"data": {"1": "747", "0": "740", "3": "750", "2": "883", "4": "769"}, "success": "true"}
If you want to have the structure in the json string preserved you can look into this link. That will make the decoding a little bit more complex.

Looping through dict elements in python [duplicate]

This question already has answers here:
python: read json and loop dictionary
(2 answers)
Closed 6 years ago.
I have a piece of json which was converted to a dict using the json function.
From this:
{
"imageIds": [
{
"imageTag": "1.2",
"imageDigest": "sha256:8b67b1691b29e27a5ccbd6fea5c97c951a025ccd45b26d4c24567ca3c4c0f13b"
},
{
"imageTag": "1.0",
"imageDigest": "sha256:aa52a12bd6e516659452af5b9ed0fad8659f9e0cea6a986c6bfe02af388df189"
}
]
}
To this:
>>> print data
{u'imageIds': [{u'imageTag': u'1.2', u'imageDigest': u'sha256:8b67b1691b29e27a5ccbd6fea5c97c951a025ccd45b26d4c24567ca3c4c0f13b'}, {u'imageTag': u'1.0', u'imageDigest': u'sha256:aa52a12bd6e516659452af5b9ed0fad8659f9e0cea6a986c6bfe02af388df189'}]}
In this example the number of keys (imageIds) is fixed but there could be any amount of imageTags under imageIds.
What I'm trying to do is loop through the 'imageTag' elements to read the tag number and perform an operation. If i wanted to loop through the key it seems straightforward with something simple like:
for key in data:
print key, 'corresponds to', data[key]
However I'm uncertain on how I loop through the items under the key.
What I want to achieve is to print out:
1.2
1.0
Iterate over inner dict the same way you do for the outer one:
for key, value in data.iteritems():
#now value can be a dictionary as well
#for innerkey, innervalues in value[0].iteritems():
# print innerkey, innervalues
#in order to only print the elements that have imageTag as the key, simply do:
print value[0]['imageTag']

How to json.loads as list instead of dictionary in Python [duplicate]

This question already has answers here:
Can I get JSON to load into an OrderedDict?
(6 answers)
Closed 9 years ago.
I have problem in reading json from file using python. The data are stored in dictionary that makes unsorted. I want to store the data in list variable to be in right sequence.
flookup = open('lookup.json')
self.tags = json.loads(flookup.read())
flookup.close()
self.tags contains data not ordered based on lookup.json file
{
"JournalTitle": "Journal Title",
"PubCode": "Pub Code",
"UniqueDocumentID": "Unique Document ID"
}
import collections, json
data = '{"a":1, "b": 2}'
print json.JSONDecoder(object_pairs_hook=collections.OrderedDict).decode(data)
prints
OrderedDict([(u'a', 1), (u'b', 2)])
(Though it seems a bit strange to require such a thing. If order is significant, JSON data should be in an array.)

Categories