Python replace nested dictionary in a dictionary - python

I'd like to replace a dictionary in a dictionary, but when I try I keep getting quotes and slashes around the added dictionary.
current_dict = {"header": {"from": "/app/off_grid_control/subscribe",
"messageId": "ef6b8e50620ac768569f1f7abc6507a5", "method": "SET",
"namespace": "Appliance.Control.ToggleX", "payloadVersion": 1,
"sign": "e48c24e510044d7e2d248c68ff2c10ca", "timestamp": 1601908439,
"triggerSrc": "Android"}, "payload": {"togglex": {"channel": 0, "onoff": 1}}}
raw_payload = {"togglex": {"channel": 0, "onoff": 1}}
payload = json.dumps(raw_payload)
From a print statement I get:
payload = {"togglex": {"channel": 0, "onoff": 0}}
So that looks fine.
Then I try and add the new dictionary part into the original dictionary:
current_dict["payload"] = payload
And get this:
current_dict = {"header": {"from": "/app/off_grid_control/subscribe",
"messageId": "ef6b8e50620ac768569f1f7abc6507a5", "method": "SET",
"namespace": "Appliance.Control.ToggleX", "payloadVersion": 1,
"sign": "e48c24e510044d7e2d248c68ff2c10ca", "timestamp": 1601908439,
"triggerSrc": "Android"}, "payload": "{\"togglex\": {\"channel\": 0, \"onoff\": 0}}"}
Noting all the added " and \ around the payload values.
Can someone please help with out to add a different dictionary to "payload" cleanly?

when you do:
payload = json.dumps(raw_payload)
you're converting your dict to a json string that only looks like a dictionary.
if you want to add it to an outer dict as a python object, you need to to do it like this:
current_dict["payload"] = json.loads(payload)

Related

How to get the value from particular key using python?

resp = {
"Name": "test",
"os": "windows",
"Agent": {
"id": "2",
"status": [
{
"code": "123",
"level": "Info",
"displayStatus": "Ready",
"message": "running",
"time": "2022-01-18T09:51:08+00:00"
}
]
}
I am trying to get the time value from the JSON.
I tried the below code but faced error with dict
resp1 = json.loads(resp)
resp2 = resp1.values()
creation_time = resp2.get("Agent").get("status")
val= creation_time["time"]
print(val) ## Thrwoing error as dict_values has no 'get'
Any suggestion on python how to take this time values
Few problems I noticed
You are trying to load a Dict type using the json's loads function which is supposed to get a string in json format (ex: '{ "name":"John", "age":30, "city":"New York"}')
You tried to access resp2 before declaration (I guessed you meant "resp1?")
You're using resp3 without declaration.
You are missing }
You don't need the .value() function because it will return a list.
Also creation time is a list with one object, so you need to access it too.
Considering all this, you can change it as follows:
import json
resp = '{ "Name": "test", "os": "windows","Agent": {"id": "2","status": [{"code": "123","level": "Info","displayStatus": "Ready","message": "running","time": "2022-01-18T09:51:08+00:00"}]}}'
resp1 = json.loads(resp)
creation_time = resp1.get("Agent").get("status")
val= creation_time[0]["time"]
print(val)
You just need to access the dicts using [] like so:
resp = {"Name": "test", "os": "windows", "Agent": {"id": "2","status": [{"code": "123","level": "Info","displayStatus": "Ready","message": "running","time": "2022-01-18T09:51:08+00:00"}]}}
creation_time = resp["Agent"]["status"]
val= creation_time[0]["time"]
print(val)
Output:
2022-01-18T09:51:08+00:00

I have to send the content of a list to a string

I have to send the content of a list to a single string.
I've tried using a loop, but only could print the result:
for item in output_list:
for line in item['output'].split('\n'):
print(line)
that is the list
output_list =
{
"jsonrpc": "2.0",
"result": [
{},
{
"tablesLastChangeTime": 1483721367.4560423,
"tablesAgeOuts": 0,
"tablesInserts": 3,
"lldpNeighbors": [
{
"ttl": 120,
"neighborDevice": "HP830_LSW",
"neighborPort": "GigabitEthernet1/0/12",
"port": "Ethernet47"
},
{
"ttl": 120,
"neighborDevice": "HP_5500EI",
"neighborPort": "GigabitEthernet2/0/22",
"port": "Ethernet48"
},
{
"ttl": 120,
"neighborDevice": "HP_5500EI",
"neighborPort": "GigabitEthernet1/0/24",
"port": "Management1"
}
],
"tablesDeletes": 0,
"tablesDrops": 0
}
],
"id": "EapiExplorer-1"
}
I want to send the content of a list to a single string.
The json module contains a method called 'dumps' which can take in your dictionary and return a string.
import json
my_string = json.dumps(output_list)
There are a couple of methods here you could use. The first is to generically pretty-print:
import pprint
...
pprint.pprint(output_list)
The second is to output in json format, since your output_list looks like it belongs that way:
import json
...
print(json.dumps(output_list))

Recursive update of a oldvalue to a new value in a nested JSON without knowing the Keypath

I am new to test python and so my question is simple, but I couldn't find an easy way to do this: I have a nested JSON in a file and I need to find a value ( not the Key) and replace it with a new value. Here I do not care about the Key path. I tried reading JSON as String and used string.replace(XXX,newvalue), it worked but it replaced the double quotes with single quotes around the Key value pairs. But I need the JSON string with the new value.
This is just a sample JSON, but it can as nested as it could be. Any guidance is appreciated.
{ "type": "postData",
"data": {
"postId":"XXX",
"postTimestamp": "1521543600",
"pageType": "/home.php:topnews",
"viewTime": 1521545993647,
"gender": 3,
"likes": "8",
"comments_shares_viewes": ["1"],
"posters": [{"type": "XXX",
"id": "695e45affa1e07529ac917f6d573a"} ],
"postImg": 1,
"postDesc": [XXX],
"origLink": 0,
"duration": 0,
"timestamp": 1521545993647},
"back_time": 1521545993693},
{"type": "saveLooked",
"data": {
"duration": 18,
"timestamp": 1521545993656,
"sessionId": XXX,
"gender": 2},
"back_time": 1521546011657}
The Code I tried was:
def Construct_JSONString(JString,klist,vlist):
s = str(JString)
klen= len(klist)
for i in range(0,klen):
OldValue= klist[i]
NewValue= vlist[i]
s= s.replace(OldValue, NewValue)
return s
You can try this -
import json
new_json_with_replaced_values=json.dumps(your_json).replace("XXX", "newvalue")

Index JSON searches python

I have the next JSON that I get from a URL:
[{
"id": 1,
"version": 23,
"external_id": "2312",
"url": "https://example.com/432",
"type": "typeA",
"date": "2",
"notes": "notes",
"title": "title",
"abstract": "dsadasdas",
"details": "something",
"accuracy": 0,
"reliability": 0,
"severity": 12,
"thing": "32132",
"other": [
"aaaaaaaaaaaaaaaaaa",
"bbbbbbbbbbbbbb",
"cccccccccccccccc",
"dddddddddddddd",
"eeeeeeeeee"
],
"nana": 8
},
{
"id": 2,
"version": 23,
"external_id": "2312",
"url": "https://example.com/432",
"type": "typeA",
"date": "2",
"notes": "notes",
"title": "title",
"abstract": "dsadasdas",
"details": "something",
"accuracy": 0,
"reliability": 0,
"severity": 12,
"thing": "32132",
"other": [
"aaaaaaaaaaaaaaaaaa",
"bbbbbbbbbbbbbb",
"cccccccccccccccc",
"dddddddddddddd",
"eeeeeeeeee"
],
"nana": 8
}]
My code:
import json
import urllib2
data = json.load(urllib2.urlopen('http://someurl/path/to/json'))
print data
I want to know how to access to the part "abstract" of the object that has "id" equal to 2 for example. The part "id" is unique so I can use id to index my searchs.
Thanks!
Here's one way to do it. You can create a generator via a generator expression, call next to iterate that generator once, and get back the desired object.
item = next((item for item in data if item['id'] == 2), None)
if item:
print item['abstract']
See also Python: get a dict from a list based on something inside the dict
EDIT : If you'd like access to all elements of the list that have a given key value (for example, id == 2) you can do one of two things. You can either create a list via comprehension (as shown in the other answer), or you can alter my solution:
my_gen = (item for item in data if item['id'] == 2)
for item in my_gen:
print item
In the loop, item will iterate over those items in your list which satisfy the given condition (here, id == 2).
You can use list comprehention to filter:
import json
j = """[{"id":1,"version":23,"external_id":"2312","url":"https://example.com/432","type":"typeA","date":"2","notes":"notes","title":"title","abstract":"dsadasdas","details":"something","accuracy":0,"reliability":0,"severity":12,"thing":"32132","other":["aaaaaaaaaaaaaaaaaa","bbbbbbbbbbbbbb","cccccccccccccccc","dddddddddddddd","eeeeeeeeee"],"nana":8},{"id":2,"version":23,"external_id":"2312","url":"https://example.com/432","type":"typeA","date":"2","notes":"notes","title":"title","abstract":"dsadasdas","details":"something","accuracy":0,"reliability":0,"severity":12,"thing":"32132","other":["aaaaaaaaaaaaaaaaaa","bbbbbbbbbbbbbb","cccccccccccccccc","dddddddddddddd","eeeeeeeeee"],"nana":8}]"""
dicto = json.loads(j)
results = [x for x in dicto if "id" in x and x["id"]==2]
And then you can print the 'abstract' values like so:
for result in results:
if "abstract" in result:
print result["abstract"]
import urllib2
import json
data = json.load(urllib2.urlopen('http://someurl/path/to/json'))
your_id = raw_input('enter the id')
for each in data:
if each['id'] == your_id:
print each['abstract']
In the above code data is list and each is a dict you can easily access the dict object.

python - exporting dictionary(array) to json

I have an array of dictionaries like so:
myDict[0] = {'date':'today', 'status': 'ok'}
myDict[1] = {'date':'yesterday', 'status': 'bad'}
and I'm trying to export this array to a json file where each dictionary is its own entry. The problem is when I try to run:
dump(myDict, open("test.json", "w"))
It outputs a json file with a number prefix before each entry
{"0": {"date": "today", "status": "ok"}, "1": {"date": "yesterday", "status": "bad"} }
which apparently isn't legal json since my json parser (protovis) is giving me error messages
Any ideas?
Thanks
Use a list instead of a dictionary; you probably used:
myDict = {}
myDict[0] = {...}
You should use:
myList = []
myList.append({...}
P.S.: It seems valid json to me anyways, but it is an object and not a list; maybe this is the reason why your parser is complaining
You should use a JSON serializer...
Also, an array of dictionaries would better serialize to something like this:
[
{
"date": "today",
"status": "ok"
},
{
"date": "yesterday",
"status": "bad"
}
]
That is, you should just use a JavaScript array.

Categories