How to Combine two JSON files? [duplicate] - python

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.

Related

Python3 - Parse list of strings inside nested json

Python Noob here. I saw many similar questions but none of it my exact use case. I have a simple nested json, and I'm trying to access the element name present inside metadata. Below is my sample json.
{
"items": [{
"metadata": {
"name": "myname1"
}
},
{
"metadata": {
"name": "myname1"
}
}
]
}
Below is the code That I have tried so far, but not successfull.
import json
f = open('./myfile.json')
x = f.read()
data = json.loads(x)
for i in data['items']:
for j in i['metadata']:
print (j['name'])
It errors out stating below
File "pythonjson.py", line 8, in
print (j['name']) TypeError: string indices must be integers
When I printed print (type(j)) I received the following o/p <class 'str'>. So I can see that it is a list of strings and not an dictinoary. So now How can I parse through a list of strings? Any official documentation or guide would be much helpful to know the concept of this.
Your json is bad, and the python exception is clear and unambiguous. You have the basic string "name" and you are trying to ... do a lookup on that?
Let's cut out all the json and look at the real issue. You do not know how to iterate over a dict. You're actually iterating over the keys themselves. If you want to see their values too, you're going to need dict.items()
https://docs.python.org/3/tutorial/datastructures.html#looping-techniques
metadata = {"name": "myname1"}
for key, value in metadata.items():
if key == "name":
print ('the name is', value)
But why bother if you already know the key you want to look up?
This is literally why we have dict.
print ('the name is', metadata["name"])
You likely need:
import json
f = open('./myfile.json')
x = f.read()
data = json.loads(x)
for item in data['items']:
print(item["metadata"]["name"]
Your original JSON is not valid (colons missing).
to access contents of name use "i["metadata"].keys()" this will return all keys in "metadata".
Working code to access all values of the dictionary in "metadata".
for i in data['items']:
for j in i["metadata"].keys():
print (i["metadata"][j])
**update:**Working code to access contents of "name" only.
for i in data['items']:
print (i["metadata"]["name"])

How to store several values in JSON [duplicate]

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"}}}

Multi-level dictionary creation [duplicate]

This question already has answers here:
What is the best way to implement nested dictionaries?
(22 answers)
Closed 4 years ago.
sample input in place of separate_function:
separate_function = [('primary_1', 'val_1'), ('primary_1', 'val_2'), ('primary_3', 'val_2')]
Expected output i.e. my_dictionary:
{
"main": {
"primary_1": [
"val_1",
"val_2"
],
"primary_3": [
"val_2"
]
}
}
I want to create a dictionary, my_dictionary like above.
There are multiple keys like "main" in the expected output. To reduce the complexity of the problem, I have hard-coded it.
There is a generator function on which I need to iterate over to create this format. Again for simplicity, I have shown that as a list of tuples. I have tried so far:
from collections import defaultdict
my_dictionary = defaultdict(dict)
for primary_var, value in separate_function:
my_dictionary['main'][primary_var].append(value)
# This would have worked if I have expected values as string
# rather than a list in that case I can write the above line like this:
my_dictionary['main'][primary_var] = value
try, except can be used and if KeyError then assign first else append can be done, However, I am looking for a better clean solution. Please suggest. Thanks.
You can use dict.setdefault to initialize a new dict key with a new list:
my_dictionary = {'main': {}}
for k, v in separate_function:
my_dictionary['main'].setdefault(k, []).append(v)
my_dictionary would become:
{'main': {'primary_1': ['val_1', 'val_2'], 'primary_3': ['val_2']}}
This is one approach using collections.defaultdict.
Demo:
from collections import defaultdict
separate_function = [('primary_1', 'val_1'), ('primary_1', 'val_2'), ('primary_3', 'val_2')]
result = defaultdict(list)
for k, v in separate_function:
result[k].append(v)
my_dictionary = {"main": result}
print(my_dictionary)
Output:
{'main': defaultdict(<type 'list'>, {'primary_3': ['val_2'], 'primary_1': ['val_1', 'val_2']})}

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