parse json nested dictionaries within array - json

How to convert
json_decode = [{"538":["1,2,3","hello world"]},{"361":["0,9,8","x,x,y"]}]
to
{"538":["1,2,3","hello world"],"361":["0,9,8","x,x,y"]}
in python?

If it is guaranteed that json_decode is a list of dictionaries, you can get your desired output with the following:
dict([list(x.items())[0] for x in json_decode])
I hope this helps.

I guess you use something like:
def merge_dicts(dict1, dict2):
return dict(list(dict1.items()) + list(dict2.items()))
l = [{"538":["1,2,3","hello world"]},{"361":["0,9,8","x,x,y"]}]
print merge_dicts(l[0], l[1])
Output:
{'361': ['0,9,8', 'x,x,y'], '538': ['1,2,3', 'hello world']}

Related

How to retrieve data from an external nested json file on seed.rb

I want to retrieve data from an external nested JSON file on my seed.rb
The JSON looks like this:
{"people":[{"name":"John", "age":"23"}, {"name":"Jack", "age":"25"}]}
I saw a solution on GitHub but it only works on non-nested JSON.
Let's say you have JSON file db/seeds.json:
{"people":[{"name":"John", "age":"23"}, {"name":"Jack", "age":"25"}]}
You can use it like this in your db/seeds.rb:
seeds = JSON.parse(Rails.root.join("db", "seeds.json"), symbolize_names: true)
User.create(seeds[:people])
seeds[:people] in this case is array of hashes with user attributes
if you have:
json_data = {"people":[{"name":"John", "age":"23"}, {"name":"Jack", "age":"25"}]}
when you do:
json_data[:people]
you'll get an array:
[{:name=>"John", :age=>"23"}, {:name=>"Jack", :age=>"25"}]
if you want to use this array to populate a model, you can do:
People.create(json_data[:people])
if you want to read each item values, you can iterate through your data, like:
json_data[:people].each {|p| puts p[:name], p[:age]}

how to convert group by(values) to json - django

i'm trying to convert my grouped by (values in django) data into JsonResponse but it raise this error :
AttributeError: 'dict' object has no attribute 'f_type'
this is my function of loadding json data
def load_cate(request):
lists = Room.objects.values('f_type','room_type', 'beds', 'balcon').annotate(total=Count('pk')).order_by('-total')
data = []
for i in lists.values():
item = {
'wc_type':i.f_type,
'room_type':i.room_type,
'beds':i.beds,
'balcon':i.balcon,
'total':i.total
}
data.append(item)
return JsonResponse({'success':True,'data':data})
is there something i did wrong ? or its different for group by values ?!
thanks in advance ..
There is no need to loop throught objects. You just need to convert QuerySet into a list.
values() will return a QuerySet object which cant be return in a JsonResponse. So just convert into a list.
lists = Room.objects.values('f_type','room_type', 'beds', 'balcon').annotate(total=Count('pk')).order_by('-total')
lists = list(lists)

How to use loops to extract elements from JSON in Python?

json_data = [{'User_Info':[{'Name':'John'},{'Name':'Ashly'},
{'Name':'Herbert'}]},
{'User_Info':[{'Name':''}]},
{'User_Info':[{'Name':'Lee'},{'Name':'Patrick'},{'Name':'Herbert'}]},
{'User_Info':[{'Name':'Benjamine'}]}]
I have JSON data and the length of the data is 5. I'd like to use loops to find names from that data. I've tried the code below but didn't get the expected outputs:
names_outputs = []
for ppl in json_data:
for i in ppl['User_Info']:
names_outputs.append(i['Name'])
print(names_outputs)
>>['John','Ashly','Herbert','Lee','Patrick','Walter','Steve','Benjamine']
However, my expected outputs should be like this:
[['John','Ashly','Herbert'],[],['Lee','Patrick','Herbert'],['Walter','Steve'],['Benjamine']]
You can use a nested list comprehension for that:
>>> [[name["Name"] for name in people] for people in [d["User_Info"] for d in json_data]]
[['John', 'Ashly', 'Herbert'], [''], ['Lee', 'Patrick', 'Herbert'], ['Benjamine']]
If you want to eliminate empty strings, use filter:
>>> [filter(None, [name["Name"] for name in people]) for people in [d["User_Info"] for d in json_data]]
[['John', 'Ashly', 'Herbert'], [], ['Lee', 'Patrick', 'Herbert'], ['Benjamine']]

Convert Multiple JSON Objects to JSON Array

I have generated a JSON file from data source which is of the format.
{}{}{}
I wish to convert this format to comma separated JSON Array as. [{},{},{}].
End goal is to push the JSON data [{},{},{}] to MongoDB.
My pythoin solution (although naive) looks something like this:
def CreateJSONArrayFile(filename):
print('Opening file with JSON data')
with open(filename) as data_file:
raw_data = data_file.read()
tweaked_data = raw_data.replace('}{', '}^|{')
split_data = tweaked_data.split('^|')
outfile = open('split_data.json', 'w')
outfile.write('[')
for item in split_data:
outfile.write("%s," % item)
outfile.write(']')
print('split_data.json Created with JSON Array')
The above code is giving me wrong results.
Can you please help me optimize the solution? Please let me know if you need more details from my end.
I'm with davedwards on this one, but if not an option -- I think this gets you what you are after.
myJson = """{"This": "is", "a": "test"} {"Of": "The", "Emergency":"Broadcast"}"""
myJson = myJson.replace("} {", "}###{")
new_list = myJson.split('###')
print(new_list)
yields:
['{"This": "is", "a": "test"}', '{"Of": "The", "Emergency":"Broadcast"}']
Not saying it is the most elegant way : )

Perl to JSON, with key/value pairs

I am trying to output some data from Perl to JSON. I can do a simple output, but would like to structure it better.
I have an array with an id, a start time and an end time. This is the code I am using to output:
print header('application/json');
my $json->{$entry} = \#array;
my $json_text = to_json($json);
print $json_text;
Which returns:
{"Season":[["1","1330065300","1344038401"],["7","1298505601","1312416001"]]}
But I would like to output something more like:
{"Season":0[{"id":1,"DateStart":1330065300,"DateEnd":1344038401},{"id":7,"DateStart":1298505601,"DateEnd":1312416001}]}
Can anyone help on how to better structure my output?
---UPDATE------
Thanks Michael. I have tried to implement your example.
This is the code at the moment:
foreach my $key (keys %$seasons)
{
$seasons->{$key} =
[
map
{
{ id=>$_[0], DateStart=>$_[1], DateEnd=>$_[2] }
} #{$seasons->{$key}}
];
}
But it returns the error (referring to the foreach line):
Not a HASH reference at line 148
$seasons is an arrayref return from a SQL fetchall_arrayref
Any clues?
You basically want to convert an array of arrays to an array of hashes, and you can do this using map. Assuming $data is your structure, this should do it:
for my $key (keys %$data) {
$data->{$key} = [
map {
{ id => $_->[0], DateStart => $_->[1], DateEnd => $_->[2] }
} #{$data->{$key}}
];
}
If you want to output an array of objects with key/value pairs instead of an array of arrays, then put appropriate data into to_json in the first place.
i.e. an array of hashrefs and not an array of arrayrefs.
You can use map to transform the data.
Whenever you're trying something like this, always check CPAN to see if someone has done it before and not try to reinvent the wheel. I found a module called JSON that seems to do exactly what you want.
There's an example on that page that does exactly what you want. Here's a quick paraphrase:
use JSON; # imports encode_json, decode_json, to_json and from_json.
# simple and fast interfaces (expect/generate UTF-8)
my $utf8_encoded_json_text = encode_json \#array;
Can't get easier than that. The best part is that this will work no matter how complex your array structure gets.