jsobj["a"]["b"]["e"].append({"f":var3, "g":var4, "h":var5})
jsobj["a"]["b"]["e"].append({"f":var6, "g":var7, "h":var8})
Answer from DrTyrsa on Stack Overflowjsobj["a"]["b"]["e"].append({"f":var3, "g":var4, "h":var5})
jsobj["a"]["b"]["e"].append({"f":var6, "g":var7, "h":var8})
Just add the dictionary as a dictionary object not a string :
jsobj["a"]["b"]["e"].append(dict(f=var3))
Full source :
var1 = 11
var2 = 32
jsonobj = {"a":{"b":{"c": var1,
"d": var2,
"e": [],
},
},
}
var3 = 444
jsonobj["a"]["b"]["e"].append(dict(f=var3))
jsonobj will contain :
{'a': {'b': {'c': 11, 'd': 32, 'e': [{'f': 444}]}}}
I would do this:
data["list"].append({'b':'2'})
so simply you are adding an object to the list that is present in "data"
Elements are added to list using append():
>>> data = {'list': [{'a':'1'}]}
>>> data['list'].append({'b':'2'})
>>> data
{'list': [{'a': '1'}, {'b': '2'}]}
If you want to add element to a specific place in a list (i.e. to the beginning), use insert() instead:
>>> data['list'].insert(0, {'b':'2'})
>>> data
{'list': [{'b': '2'}, {'a': '1'}]}
After doing that, you can assemble JSON again from dictionary you modified:
>>> json.dumps(data)
'{"list": [{"b": "2"}, {"a": "1"}]}'
As mentioned in the comments, once loaded the json is a python dictionary. You should now iterate on the value of the 'data' key, extract the information and store them in a list.
Something like this should do the job:
json_obj = json.load(json1)
ips = []
for piece in json_obj['data']:
this_ip = [piece['custom3'], piece['modemId']]
ips.append(this_ip)
One line form:
ips = [[piece['custom3'], piece['modemId']] for piece in json_obj['data']]
If you just want this
ips = [["custom3","modemId"],["custom3","modemId"]]
Then all you need is a simple list comprehension
ips = [d.keys() for d in json1_obj['data']]
If you want to actually get the values (in order), not the keys
ips = [ [ d['custom3'], d['modemId'] ] for d in json1_obj['data']]
The trouble is that you are dumping your data to JSON inside GenIndentifier, then appending that JSON string to a list.
Instead you should move the JSON conversion out of that function, and do it at the end:
def GenIndentifier(options):
data = [identifier, hex_dig]
return data
data = []
for i in range(0, 2, 1):
...
data.append(GenIndentifier(options))
data = json.dumps(data)
print data
When you call json.dumps() it converts the object, in this case a list of 2 elements, to a JSON formatted string. You are then taking that list of strings, and appending them to a list.
If what you are looking for is a single JSON formatted list of lists, you would want to avoid doing the json.dumps() inside the GenIdentifier object, and simply return a list from that function. Then at the end, where you do the print data, instead do print json.dumps(data)
def GenIndentifier(options):
data=[identifier,hex_dig]
return data
data=[]
for i in range(0,2,1):
...
data.append(GenIndentifier(options))
data = json.dumps(data)
print data
This will result in the following:
[["27780741708467800000000", "f798d2cd9aec1b98fb48b34fd249fe19c06a4a1d"],
["27780741708467800000001", "e5073922dbb7a278769d52277d49c6ad3017b1ba"]]
Just read the file (not r+ which is read/write), make the change, then open the file for writing and write it. This will overwrite the original file instead of appending to it.
Note that .append returns None and modifies the list in-place, so assigning to change doesn't work.
Here's the correct code:
import json
#any number
id = 1234
with open("values.json") as file:
data = json.load(file)
data["values"].append(id)
with open("values.json", "w") as file:
json.dump(data, file)
When using json.dump(), you must dump the entire JSON data into the file; not just the change. Here is the code:
import json
#any number
id = 1234
with open("values.json", "r+") as file:
data = json.load(file)
data["filter"].append(id)
json.dump(data, file)
{"language": "['English', 'French']", "bank": 50}
Here the "language" keys hold a string rather than a list because of the " before [ and " after ]. To solve this, change the file to this:
{"language": ["English", "French"], "bank": 50}
Then use this code to append "Spanish" or any language from now on:
import json
with open("temp.json", "r") as f:
data = json.load(f)
data["language"].append("Spanish")
with open("temp.json", "w") as f:
json.dump(data, f)
import json
import ast
with open("example.json", "r") as jsonFile:
data = json.load(jsonFile)
#data={"language": "['English', 'French']", "bank": 50}
#take a variable e
e=ast.literal_eval(data['language'])
e.append('Spanish')
data['language']=e
print(data)
#{'language': ['English', 'French', 'Spanish'], 'bank': 50}
Just adding onto alexce's response, you can easily convert the restructured data into JSON:
import json
json.dumps(result)
There are some potential security concerns with top-level arrays. I'm not sure if they're still valid with modern browsers, but you may want to consider wrapping it in an object.
import json
json.dumps({'results': result})
To solve this, you need to split the input list into chunks, by 7 in your case. For this, let's use this approach. Then, use a list comprehension producing a list of dictionaries:
>>> from pprint import pprint
>>> l = [['String 1'],['String 2'],['String 3'],['String 4'],['String 5'],
... ['String 6'],['String 7'],['String 8'],['String 9'],['String 10'],
... ['String 11']]
>>> def chunks(l, n):
... """Yield successive n-sized chunks from l."""
... for i in range(0, len(l), n):
... yield l[i:i+n]
...
>>>
>>> result = [{"title%d" % (i+1): chunk[i][0] for i in range(len(chunk))}
for chunk in chunks(l, 7)]
>>> pprint(result)
[{'title1': 'String 1',
'title2': 'String 2',
'title3': 'String 3',
'title4': 'String 4',
'title5': 'String 5',
'title6': 'String 6',
'title7': 'String 7'},
{'title1': 'String 8',
'title2': 'String 9',
'title3': 'String 10',
'title4': 'String 11'}]