I've been trying to figure out the best way to handle the conversion from list to well-formatted JSON.
I have the list called 'headers' that can include x number of tuples, which are always formatted in such a way that headers[x][0] is a key, and headers[x][1] is a value.
Essentially, I need something that converts the list of tuples into JSON of key-value pairs, where output looks something like this:
Using json module:
headers = [('Subject', 'Homebrew & Mold'), ('Line', '13')]
import json
result = json.dumps(dict(headers))
print(result)
OUTPUT:
{"Subject": "Homebrew & Mold", "Line": "13"}
One-liner using list-comprehension:
print([{x[0]: x[1]} for x in headers])
OUTPUT:
[{'Subject': 'Homebrew & Mold'}, {'Line': '13'}]
I would be something like:
import json
headers = [('Subject', 'Homebrew & Mold'), ('Line', '13')]
results = []
for item in headers:
results.append(dict([item]))
jsonified = json.dumps(results)
Output:
[{"Subject": "Homebrew & Mold"}, {"Line": "13"}]
It can be further simplified, a little. But, you'll get an idea.
Related
here is the json: (FYI, the '0' to '2' is the index of the original pd.Series([1,1,1])
json1 = {
'hi':[
{'0':1},
{'1':1},
{'2':1}
]
}
I want to get [1,1,1] from json1.
I tried:
records = [v for v in json1['hi']]
emt=[]
for rec in records:
for i in rec.keys():
value = rec[i]
emt.append(value)
is there a simple and easy way like one line of code to achieve it? Thanks
You can use dict.values:
list(map(next, map(iter, map(dict.values, json1['hi']))))
Although this will only work if there's one key in each dict. Otherwise you can use itertools.chain:
list(chain(*map(dict.values, json1['hi'])))
json1['hi'] returns a list
From that list, you have dictionaries.
In each dictionary, you want the first and only value, which can be done with next(iter(iterable))
[next(iter(x.values())) for x in json1['hi']]
If your data type is inconvenient:
json1 = {
'hi':[
{'0':1},
{'1':1},
{'2':1}
]
}
then the code to extract the data you want will also be inconvenient:
[next(iter(d.values())) for d in json1["hi"]]
If your data type is convenient:
json1 = {
'hi':{'0':1,
'1':1,
'2':1}
}
then the code will also be convenient:
list(json1['hi'].values())
Moral of the story: use a dictionary, not a list of one-element dictionaries.
Since you like short code:
[*map(lambda x: list(x.values())[0], json1['hi'])]
[1, 1, 1]
I need to append dictionary values to an already existing JSON file. How can I be able to do that?
My details.json File
{"name": "someName"}
Dictionary generated by my python script
list1 = {"name": "someOthername"}
with open("details.json") as r:
data = json.load(r)
desirableDict = data.append(list1) # It has to be something like this
print(desirableDict)
Desirable Output: {"name": ["someName", "someOthername"]}
You can check all keys within a for loop and put the values of the json file and list1 inside a list like this:
import json
list1 = {"name": "someOthername"}
with open("details.json") as file:
data = json.load(file)
desirableDict = data.copy()
for key in data:
if key in list1:
if type(data[key]) is list:
data[key].append(list1[key])
else:
desirableDict[key] = [data[key],list1[key]]
print(desirableDict)
It seems like you need deep merging of structures. I would like to recommend you to use this awesome library https://pypi.org/project/deepmerge/.
There are a lot of examples like you want to achieve.
from deepmerge import always_merger
base = {"foo": ["bar"]}
next = {"foo": ["baz"]}
expected_result = {'foo': ['bar', 'baz']}
result = always_merger.merge(base, next)
assert expected_result == result
I have the JSON which looks like this:-
{
"name": "PT",
"batservers": [
{"name": "bat1", "qmchannel": "abcd", "mount": "efgh"},
{"name": "bat2", "qmchannel": "abcd", "mount": "efgh"},
{"name": "bat3", "qmchannel": "abcd", "mount": "efgh"},
]
}
I want to retrieve the value of "name" present in all the dictionary and save it in a list variable i.e. ["bat1","bat2","bat3"]
I tried something like this:-
batsList = env["batservers"][0:]["name"]
but it displays the below error:-
TypeError: list indices must be integers or slices, not str
I know I can do this using a loop but can someone please help me to do using in a single line code way which I am trying above?
Thanks,
SUYASH GUPTA.
You can't do it without a loop. But the loop can be a list comprehension:
batsList = [b['name'] for b in env["batservers"]
How about saving the list as:
list_of_names = [x[name] for x in env["batservers"]]
Try this:
[b['name'] for b in env['batservers']]
Or this:
map(lambda b: b['name'], env['batservers'])
[0:] doesn't do much for you: it returns the same array of dictionaries.
env["batservers"][0:] returns a list, and you can't access directly the values of the dicts in the list.
You can use a list comprehension:
names = [elem["name"] for elem in env["batservers"]]
This is a basic solution using a for loop to iterate over the sub dictionary and appending to the empty list res.
res = []
for item in env["batservers"]:
res.append(item["name"])
print (res) #=> ['bat1', 'bat2', 'bat3']
I have a JSON response from the website shown below. I want to print the 'value' and 'datetime' keys of data. I am not able to access these two elements in JSON response.
data= {"parameter_name":"Inst",
"parameter_code":"WL1","data":[
{"value":3.1289999485,"datetime":"2018-07-01T00:00:00+00:00"},
{"datetime":"2018-07-01T00:30:00+00:00","value":3.1859998703},
{"value":3.33099985123,"datetime":"2018-07-01T00:45:00+00:00"},
{"datetime":"2018-07-01T01:15:00+00:00","value":3.22300004959},
{"datetime":"2018-07-01T01:45:00+00:00","value":3.32299995422}]}
my code till now
for element in len(data['data']):
date = element['datetime']
value = element['value']
print value, date
I am getting error
for element in len(data['data']):
TypeError: string indices must be integers, not str
What you've shown as your JSON data is likely not the actual value of data. If you attempt to access the data like a Python dict, it raises TypeError: string indices must be integers, not str. Your JSON data probably looks like this (notice the quotes):
# This is JSON, essentialy a string in the format of a Python dict.
data = """{
"parameter_name": "Inst",
"parameter_code": "WL1",
"data":[
{
"value":3.1289999485,
"datetime":"2018-07-01T00:00:00+00:00"
},
{
"datetime":"2018-07-01T00:30:00+00:00",
"value":3.1859998703
},
{
"value":3.33099985123,
"datetime":"2018-07-01T00:45:00+00:00"
},
{
"datetime":"2018-07-01T01:15:00+00:00",
"value":3.22300004959
},
{
"datetime":"2018-07-01T01:45:00+00:00",
"value":3.32299995422
}
]
}"""
Convert it into a Python dict by using the Python Standard Library json package:
import json
# This converts the JSON string into a Python dict
data = json.loads(data)
You can access the data and it's 'data' key, then iterate over it (like you were doing):
for element in data['data']:
print(element['value'], element['datetime'])
You can try like this:
for element in data['data']:
date = element['datetime']
value = element['value']
print(date)
print(value)
Output:
3.1289999485
2018-07-01T00:00:00+00:00
3.1859998703
2018-07-01T00:30:00+00:00
3.33099985123
2018-07-01T00:45:00+00:00
3.22300004959
2018-07-01T01:15:00+00:00
3.32299995422
2018-07-01T01:45:00+00:00
Explanation:
If you want to iterate over the elements in the list,:
for element in data['data']
If you want to iterate over the list using by their index:
for index in range(len(data['data'])):
If you have a web responce in text format you would also have to decode it first. Check
https://docs.python.org/2/library/json.html (for python 2) or https://docs.python.org/3.7/library/json.html (for python 3) to see the documentation about the json library.
You have to:
import json
decodedData = json.loads(data)
and then loop over decodedData as you've done.
I previusly asked about adding, and someone helped me out with append. My new problem is trying to delete a key with a nested list, e.g.:
JSON:
data = {"result":[{"name":"Teddy","list":{"0":"24","1":"43","2":"56"}},
{"name":"Barney","list":{"0":"24","1":"43","2":"56"}]}
Python:
name = input("Input a key to delete") #Must hold a value.
data["result"].pop(name)
E.g. Barney => then delete Barney etc.
I use the method below to find a key, but I am not sure this is the correct approach.
Finding Barney:
for key in data['result']:
if key['name'] == name:
print("Found!!!!")
I am not sure. This surely does not work, maybe I should loop through each key or? Any suggestion or code example is worth.
After Delete: Now that barney was deleted the dictionary remains like this.
data = {"result":[{"name":"Teddy","list":{"0":"24","1":"43","2":"56"}}]}
If the goal is to remove list items from the JSON document, you'll want to:
Convert the JSON document into a Python data structure
Manipulate the Python data structure
Convert the Python data structure back to a JSON document
Here is one such program:
import json
def delete_keys(json_string, name):
data = json.loads(json_string)
data['result'][:] = [d for d in data['result'] if d.get('name') != name]
json_string = json.dumps(data)
return json_string
j = '''
{"result":[{"name":"Teddy",
"list":{"0":"24","1":"43","2":"56"}},
{"name":"Barney","list":{"0":"24","1":"43","2":"56"}}]}'''
print delete_keys(j, 'Barney')
Result:
$ python x.py
{"result": [{"list": {"1": "43", "0": "24", "2": "56"}, "name": "Teddy"}]}
Note this list comprehension:
data['result'][:] = [d for d in data['result'] if d.get('name') != name]
The form l[:] = [item in l if ...] is one way to delete several items from a list according to the indicated condition.
Since data['result'] is a list, you'll have to go to the index and delete the key. If you're looking to delete the key across all indices in the list, you could quickly write a function that iterates through the list and deletes the matching key
def delete_key(list_obj, key):
for value in list_obj:
if key in value:
value.pop(key)
return list_obj
result = delete_key(data["result"], 'key1')
You can convert the JSON into a JavaScript object.
var resultString = '{'result':[{'key1':'value1','key2':'value2'}, {'key1':'value3','key2':'value4'}]}';
var result = JSON.parse(resultString);
Once you do, you should be more aware that this is an array of objects. You need to know which index you want to remove. You can use the .find method for arrays
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
if you don't know the index.
var inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
function findCherries(fruit) {
return fruit.name === 'cherries';
}
console.log(inventory.find(findCherries));
// { name: 'cherries', quantity: 5 }
Realize though that find does not work in IE. Once you know the index, you can split the array.
var myFish = ["angel", "clown", "drum", "mandarin", "surgeon"];
var removed = myFish.splice(3, 1);
// removed is ["mandarin"]
// myFish is ["angel", "clown", "drum", "surgeon"]
from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice