I am looping to convert the array of array to object, I am splitting using comma"," but if my values have some comma it is also getting split. Eg: If my value has a date May 2, 2017 it is actually a single value, but it is splitting as May 2 as one value and 2017 as another value so, my whole is object getting changed.need help
I am reading from an excel sheet. My Output is array of array. I need to convert that to a json object.
var xls = require('excel');
describe('TransactionDetails-Excel', function () {
it('External Type G Tranasaction Details validation', function (done) {
xls('transactions.xlsx', function(err, data) {
if(err){
throw err;
}
else{
console.log(data);
console.log(JSON.stringify(convertToJSON(data)));
done();
}
});
function convertToJSON(array) {
var first = array[0].join();
var headers = first.split(',');
var jsonData = [];
for ( var iterator_i = 1, length = array.length; iterator_i < length; iterator_i++ ){
var myRow = array[iterator_i].join();
var row = myRow.split(',');
var data = {};
for ( var x = 0; x < row.length; x++ ){
data[headers[x]] = row[x];
}
jsonData.push(data);
}
return jsonData;
}
});
});
Excel sheet: transactions.xlsx
click here to view screenshot of excel sheet
output: data
[ [ 'Transaction Id', 'Paid ', 'Time Created' ],
[ '0YC0',
'Joe\'s Generic Business \nperson#gmail.com',
'Mar 2, 2012 14:28:36 PST' ],
[ '8uyhr', 'mail#gmail.com', 'May 2, 2015 15:20:20 PST' ],
[ '786YUH', 'mailtome#gmail.com', 'May 18, 2017 13:20:30 PST' ] ]
Output : //this is what i get
[{"Transaction Id":"0YC0","Paid ":"Joe's Generic Business \nperson#gmail.com","Time Created":"Mar 2","undefined":" 2012 14:28:36 PST"},
{"Transaction Id":"8uyhr","Paid ":"mail#gmail.com","Time Created":"May 2","undefined":" 2015 15:20:20 PST"},
{"Transaction Id":"786YUH","Paid ":"mailtome#gmail.com","Time Created":"May 18","undefined":" 2017 13:20:30 PST"}]
But final object should be:
[{"Transaction Id":"0YC0","Paid ":"Joe's Generic Business \nperson#gmail.com","Time Created":"Mar 2, 2012 14:28:36 PST"},
{"Transaction Id":"8uyhr","Paid ":"mail#gmail.com","Time Created":"May 2, 2015 15:20:20 PST"},
{"Transaction Id":"786YUH","Paid ":"mailtome#gmail.com","Time Created":"May 18, 2017 13:20:30 PST"}]
Thanks in Advance.
use this function insted
function convertToJSON(array) {
var objArray = [];
for (var i = 1; i < array.length; i++) {
objArray[i - 1] = {};
for (var k = 0; k < array[0].length && k < array[i].length; k++) {
var key = array[0][k];
objArray[i - 1][key] = array[i][k]
}
}
return objArray;
}
You can do it easily by splitting out the labels and the data, and doing the following:
var labels = data[0]
var output = data.slice(1).map(item => item.reduce((obj, val, index) => {
obj[labels[index]] = val
return obj
}, {}))
This works by maping each item in the array to a new array. With each item undergoing a reduce that converts the data values into an object with the correct keys.
Fiddle here
Join with some custom value and then split
Replace this with
var myRow = array[iterator_i].join(';');
var row = myRow.split(';');
you can try this one also.....
let keys = array.shift();
let arrayofObjects = array.map(subArray => _.object(keys,subArray));
console.log(arrayofObjects);
Related
I am trying to find the places of each letter in a sentence by using "dictionaries". The problem is I want to find all the places that each letter is and not only the last one. I am very new to JavaScript and couldn't figure out the way to do it.
function letters(stringArgument) {
stringArgument = stringArgument.replace(/ /g,'');
var dict = {};
for (var i=0; i < stringArgument.length; i++ )
if (!stringArgument[i] in dict){
dict[stringArgument[i]] = [];
}else{
dict[stringArgument[i]] = [i+1]
}
return dict
}
var a = letters('Lost time is never found again.');
console.log(a);
naturally gives this output:
{ L: [ 1 ], o: [ 17 ], s: [ 10 ], t: [ 5 ]...
but it should give this:
{ L: [ 1 ], o: [ 2, 17 ], s: [ 3, 10 ], t: [ 4, 5 ]...
Also each letter is saved to the dictionary at the same order they appear in the sentence, how can I order the letters alphabetically?
What you need is a function that gets the positions of a character in a given string.
Try this:
function findAllPositions(char, content) {
var result = [];
let index = content.indexOf(char);
while(index !== -1) {
result.push(index);
index = content.indexOf(char, index + 1);
}
return result;
}
findAllPositions('o', 'Lost time is never found again.'); // Result = [1, 20]
Using this we can update the letter function as follows:
function letters(stringArgument) {
stringArgument = stringArgument.replace(/ /g, '');
var dict = {};
for (const char of stringArgument) {
dict[char] = findAllPositions(char, stringArgument)
}
return dict;
}
letters('is again.')
/*
{
"i": [0, 5],
"s": [1],
"a": [2, 4],
"g": [3],
"n": [6],
".": [7]
}
*/
You need to have
parantheses for the check
if (!(stringArgument[i] in dict)) {
create an array if the above is true
push the postion to the array
For getting a sorted output, you could take the entries of the object, apply a sorting by taking the key and show the result in order.
Object have an insertation oder for not positive 32 bit numbers (like indixes) or symbols. The index like numbers are sorted by value and appears first in the object.
function letters(stringArgument) {
stringArgument = stringArgument.replace(/ /g, '');
var dict = {};
for (var i = 0; i < stringArgument.length; i++) {
if (!(stringArgument[i] in dict)) {
dict[stringArgument[i]] = [];
}
dict[stringArgument[i]].push(i + 1);
}
return dict;
}
var a = letters('Lost time is never found again.');
Object
.entries(a)
.sort(([a], [b]) => a.localeCompare(b))
.forEach(([key, positions]) => console.log(key, ...positions));
console.log(a);
First, for any item, if it is not in an empty array:
var notInDict = !(stringArgument[i] in dict);
If not in dict, then initialize an empty array and push the item in it using
dict[stringArgument[i]].push(i + 1);
Try this.
function letters(stringArgument) {
stringArgument = stringArgument.replace(/ /g, "");
var dict = {};
for (var i = 0; i < stringArgument.length; i++) {
var notInDict = !(stringArgument[i] in dict);
if (notInDict) {
dict[stringArgument[i]] = [];
}
dict[stringArgument[i]].push(i + 1);
}
return dict;
}
var a = letters("Lost time is never found again.");
console.log(a);
you are assigning a new array at each iteration
dict[stringArgument[i]] = [i+1]
what you need to do is push the new position to existing array.
dict[stringArgument[i]].push(i+1)
also, remove the else block
function letters(stringArgument) {
stringArgument = stringArgument.toLowerCase().replace(/ /g,'');
var dict = {};
for (var i=0; i < stringArgument.length; i++ ){
if (!dict.hasOwnProperty(stringArgument[i])){
dict[stringArgument[i]] = [];
}
dict[stringArgument[i]].push(i+1);
}
//sorting
var letters = Object.keys(dict); //returns a array
letters.sort();
var sortedDic = {};
for(var i in letters) {
sortedDic[letters[i]] = dict[letters[i]];
}
return sortedDic;
}
var a = letters('Lost time is never found again.');
console.log(a);
for the first part you can also do that:
let sentence = 'Lost time is never found again.'
let tabLetters = [...sentence.replace(/ /g,'')].reduce((a,c,i)=>
{
if (!a[c]) a[c] = [i+1]
else a[c].push(i+1)
return a
},{})
document.write(JSON.stringify(tabLetters))
I'm looking to count the occurances of certain strings within JSON - in this instance sensorUUID.
var newDataArray = JSON.stringify(conData);
JSON
[{"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"22489710","timeStamp":1500362037.111941,"uID":"22489710_3_10"},{"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"22489710","timeStamp":1500362036.109874,"uID":"22489710_3_10"}]
I've tried the following code but it is returning an empty object.
var obj = {};
for (var i = 0, j = newDataArray.length; i < j; i++) {
if (obj[newDataArray[i].sensorUUID]) {
obj[newDataArray[i]]++;
}
}
console.log(obj);
The full JSON file will have multiple sensor ID's within it, I am looking to return the number of unique sensor ID.
e.g.
22489710 has 10 occurrences
63846683 has 23 occurrences
etc.
the if condition in for loop is correct but you have to initialize count as 1 for the first time you find a particular sensorUUID.
var newDataArray = [{"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"22489710","timeStamp":1500362037.111941,"uID":"22489710_3_10"},{"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"22489710","timeStamp":1500362036.109874,"uID":"22489710_3_10"}];
var obj = {};
for (var i = 0, j = newDataArray.length; i < j; i++) {
if (obj[newDataArray[i].sensorUUID]) {
obj[newDataArray[i].sensorUUID]++;
}else{
obj[newDataArray[i].sensorUUID] = 1;
}
}
// obj gives you count for each unique sensorUUID.
console.log(obj);
//if you want total count of all sensorUUID you can sum all the values in obj.
var count = Object.values(obj).reduce((a, b) => a + b, 0);
console.log(count);
you can set a variable count and iterate over the array using Array#forEach and check whether the object has the property sensorUUID using Object#hasOwnProperty if yes, increment the count
var data = [{"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"22489710","timeStamp":1500362037.111941,"uID":"22489710_3_10"},{"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"22489710","timeStamp":1500362036.109874,"uID":"22489710_3_10"}];
var count = 0;
data.forEach((x)=>{
if(x.hasOwnProperty('sensorUUID'))
count++;
});
console.log(count);
You can simply iterate through the json array using array.reduce and count the occurances of sensorUUID and store it inside the new object.
var json = [{
"blobJson": "x",
"deviceMfg": 10,
"eventCode": 0,
"sensorClass": 3,
"sensorUUID": "22489710",
"timeStamp": 1500362037.111941,
"uID": "22489710_3_10"
}, {
"blobJson": "x",
"deviceMfg": 10,
"eventCode": 0,
"sensorClass": 3,
"sensorUUID": "22489710",
"timeStamp": 1500362037.111941,
"uID": "22489710_3_10"
}, {
"blobJson": "x",
"deviceMfg": 10,
"eventCode": 0,
"sensorClass": 3,
"sensorUUID": "22489710123",
"timeStamp": 1500362036.109874,
"uID": "22489710_3_10"
}];
let count = json.reduce((newObj, obj) => {
if(newObj[obj.sensorUUID]) {
newObj[obj.sensorUUID] = newObj[obj.sensorUUID]+1;
} else {
newObj[obj.sensorUUID] = 1;
}
return newObj;
}, {});
console.log(count);
https://jsfiddle.net/7jjoches/1/
Using jquery method $.parseJSON you have to convert the JSON string to a JSON object and only then you can work with it.
var conData = '[{"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"22489710","timeStamp":1500362037.111941,"uID":"22489710_3_10"},{"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"22489710","timeStamp":1500362036.109874,"uID":"22489710_3_10"}]';
var newDataArray = $.parseJSON(conData);
console.dir(newDataArray);
var obj = {};
for (var i = 0; i< newDataArray.length; i++) {
obj[newDataArray[i].sensorUUID] = obj[newDataArray[i].sensorUUID] ? obj[newDataArray[i].sensorUUID]+1 : 1;
}
console.log(obj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have an array which looks like:
var data = [{"year":[1981],"weight":[3]},
{"year":[1982],"weight":[4]},
{"year":[1985],"weight":[7]}]
My data series starts with year 1980 and ends with year 1986. My task is to input all missing values into the array; in my case the final array should be:
var data = [{"year":[1980],"weight":[0]},
{"year":[1981],"weight":[3]},
{"year":[1982],"weight":[4]},
{"year":[1983],"weight":[0]},
{"year":[1984],"weight":[0]},
{"year":[1985],"weight":[7]},
{"year":[1986],"weight":[0]}]
I implemented this task in two steps. First I created an empty array with length of seven elements (for years 1980 - 1986) and initialize each element with value {"year": $CURRENT_YEAR, "weight": 0}. Then I loop through data array, find index of current year in the empty array and replace year and weight fields with current values. My code is pasted below.
I wonder if the code could be rewritten in a more elegant way.
// Create empty array
var my_array = []
var length = 7
// 1st step
year = 1980
for (var i = 0; i < length; i++) {
my_array.push({"year": year, "weight": 0});
year++
}
// 2nd step
for (var j = 0; j < data.length; j++) {
curr_year = data[j]["year"][0];
curr_weight = data[j]["weight"][0]
var index = my_array.findIndex(function(item, i) {return item.year === curr_year})
my_array[index] = {"year": curr_year, "weight": curr_weight}
}
It's best to do this job by .map() Besides if you have a large input array it might be wise to set up a hash (lut) in the first place such as;
var data = [{"year":[1981],"weight":[3]},
{"year":[1982],"weight":[4]},
{"year":[1985],"weight":[7]}],
lut = data.reduce((p,c) => p[c.year[0]] ? p : (p[c.year[0]] = c, p), {});
range = [1980,1986],
result = Array(range[1]-range[0] + 1).fill()
.map((_,i) => lut[i+range[0]] ? lut[i+range[0]] : {year: [i+range[0]], weight: [0]});
console.log(result);
You can combine the 2 loops and do both steps in one loop
// Create empty array
var my_array = []
var length = 7
year = 1980
for (var i = 0; i < length; i++) {
// check if there is data for the year
var index = data.findIndex(function(item, i) {return item.year === year});
if(index > -1){ //if there is data, use it
my_array.push({"year": data[index]["year"][0], "weight": data[index]["weight"][0]});
}else{ //put in default data
my_array.push({"year": year, "weight": 0});
}
year++;
}
Find index of element in array each time is bad performance for large data. I can suggest the following algorithm:
// Create empty object and fill it with values where keys are years
var years = {};
data.forEach(item => {
years[item.year[0]] = item.weight[0];
});
// Result array with all years
var result = [];
var startYear = 1980;
var endYear = 1986;
// Generate our result array
for (var i = startYear; i <= endYear; i++) {
// If property for given year (i) exists in "years" object then add it to "result" array
// in other case add default object with weight 0
var o = years[i] ? { year: [i], weight: [years[i]] } : { year: [i], weight: [0] };
result.push(o);
}
You could do this with just find() and while loop.
var data = [{"year":[1981],"weight":[3]},{"year":[1982],"weight":[4]},{"year":[1985],"weight":[7]}];
var i = 1980;
var result = [];
while(i <= 1986) {
var find = data.find(e => e.year[0] == i);
(find) ? result.push(find) : result.push({year: [i], weight: [0]});
i++;
}
console.log(result)
You could also first use map() to get array of years and then use while loop with indexOf().
var data = [{"year":[1981],"weight":[3]},{"year":[1982],"weight":[4]},{"year":[1985],"weight":[7]}];
var i = 1980;
var result = [];
var years = data.map(e => e.year[0]);
while(i <= 1986) {
var ind = years.indexOf(i);
(ind != -1) ? result.push(data[ind]) : result.push({year: [i], weight: [0]});
i++;
}
console.log(result)
I have an array of Date() objects in javascript and I want to count the number of events on each day.
Here is an example:
What I have is:
Array [ Date 2014-12-04T10:30:20.000Z, Date 2014-12-05T11:04:58.056Z, Date 2014-12-05T11:04:58.056Z, Date 2014-12-05T11:04:58.056Z ]
What I want is:
Array [{date: '2014-12-04', counts: 1}, {date: '2014-12-05', counts: 3}]
Thanks a lot!
Max
Basic answer:
var arr = [], // fill it with array with your data
results = {}, rarr = [], i, date;
for (i=0; i<arr.length; i++) {
// get the date
date = [arr[i].getFullYear(),arr[i].getMonth(),arr[i].getDate()].join("-");
results[date] = results[date] || 0;
results[date]++;
}
// you can always convert it into an array of objects, if you must
for (i in results) {
if (results.hasOwnProperty(i)) {
rarr.push({date:i,counts:results[i]});
}
}
These can be made much easier with lodash functions, and Array.forEach() in ES5
You much better off having a simple object with the keys as the date and the value as the count. I've added a simple pad function that prefixes a zero where the number is a single digit as per your output requirements.
function pad(n) {
return n.toString().length == 1 ? '0' + n : n;
}
function getCount(arr) {
var obj = {};
for (var i = 0, l = arr.length; i < l; i++) {
var thisDate = arr[i];
var day = pad(thisDate.getDate());
var month = pad(thisDate.getMonth() + 1);
var year = thisDate.getFullYear();
var key = [year, day, month].join('-');
obj[key] = obj[key] || 0;
obj[key]++;
}
return obj;
}
getCount(arr); // Object { 2014-04-12: 1, 2014-05-12: 3 }
DEMO
I came across the same issue and found this solution which uses Map()
`
calc = (obj) => {
const orders = []
const dates_map = new Map()
//iterate through all the objects inside the orders array
orders.forEach(order => {
// format and get the date
const date = new Date(order.created_at).toLocaleDateString('en-GB')
//check if the date key exists in the Map() and save it in a temp
const temp = dates_map.get(date) || false
// if it does not exist
if (temp) {
// clone the object
const previous = {...temp}
// increase counter
previous.count += 1
dates_map.set(date, previous)
}else{
//create new object to avoid overwriting
const result = {}
result.count = 1
dates_map.set(date, result)
}
})
console.log(dates_map)
}
And this is the output
Output: Map(3) {
'08/05/2021' => { count: 2 },
'09/05/2021' => { count: 1 },
'11/05/2021' => { count: 2,}
}
`
I've got a JSON response that looks like this:
{
"COLUMNS":["SETTING_NAME","SETTING_VALUE","COLOR"],
"DATA": [
["setting_1",100.0,"yellow"],
["setting_2",150.0,"red"],
["setting_3",30.0,"green"],
["setting_4",11.0,"blue"]
]
}
How do I find the 'color' for the setting 'setting_4'? Acceptable solutions would either be am easy way to access the data, or a function to transform this into an exploded key/value array like
[
setting_1_value: '100',
setting_1_color: 'yellow',
setting_2_value: "150"
...
]
You can use this code to put the data into the type of data structure that you asked for:
var response = {"COLUMNS":["SETTING_NAME","SETTING_VALUE","COLOR"],
"DATA":[["setting_1",100.0,"yellow"],["setting_2",150.0,"red"],
["setting_3",30.0,"green"],["setting_4",11.0,"blue"]]};
var data = response.DATA;
var columns = response.COLUMNS;
var hash = {}, item, name, i;
var cols = {};
// remember order of columns
for (i = 0; i < columns.length; i++) {
cols[columns[i]] = i;
}
// fetch data from correct column
for (i = 0; i < data.length; i++) {
item = data[i];
name = item[cols["SETTING_NAME"]];
hash[name + "_value"] = item[cols["SETTING_VALUE"]];
hash[name + "_color"] = item[cols["COLOR"]];
}
hash.num = data.length;
As you requested, this gives you a data structure like this so you can directly read any value you want:
{
"setting_1_value":100,
"setting_1_color":"yellow",
"setting_2_value":150,
"setting_2_color":"red",
"setting_3_value":30,
"setting_3_color":"green",
"setting_4_value":11,
"setting_4_color":"blue",
"num":4
}
jsFiddle here: http://jsfiddle.net/jfriend00/HZmYN/ that generated this result.
Personally, I would rather use this code to parse it into this type of data structure:
var response = {"COLUMNS":["SETTING_NAME","SETTING_VALUE","COLOR"],
"DATA":[["setting_1",100.0,"yellow"],["setting_2",150.0,"red"],
["setting_3",30.0,"green"],["setting_4",11.0,"blue"]]};
var data = response.DATA;
var columns = response.COLUMNS;
var newData = [], item, obj, i, num, match;
var cols = {};
// remember order of columns
for (i = 0; i < columns.length; i++) {
cols[columns[i]] = i;
}
for (i = 0; i < data.length; i++) {
item = data[i];
obj = {};
obj.value = item[cols["SETTING_VALUE"]];
obj.color = item[cols["COLOR"]];
obj.name = item[cols["SETTING_NAME"]];
match = obj.name.match(/\d+$/);
if (match && match.length > 0) {
obj.settingNumber = parseInt(match[0], 10);
}
newData.push(obj);
}
// now sort the array by the number in the name setting
newData.sort(function(a, b) {
return(a.settingNumber- b.settingNumber);
});
And generates this data structure:
[
{"value":100,"color":"yellow","name":"setting_1","settingNumber":1},
{"value":150,"color":"red","name":"setting_2","settingNumber":2},
{"value":30,"color":"green","name":"setting_3","settingNumber":3},
{"value":11,"color":"blue","name":"setting_4","settingNumber":4}
]
Illustrated in this jsFiddle: http://jsfiddle.net/jfriend00/A23Jd/.
The reason I prefer this structure, is you can more easily access the "n" settings as an array of objects:
newData[0].color
newData[0].value
newData[0].name
newData[1].color
....
And, it's easier to iterate through the various settings
Using $.grep will allow you to access the data without mapping them before:
var json={"COLUMNS":["SETTING_NAME","SETTING_VALUE","COLOR"],
"DATA":[["setting_1",100.0,"yellow"],
["setting_2",150.0,"red"],
["setting_3",30.0,"green"],
["setting_4",11.0,"blue"]]}
alert($.grep(json.DATA, function(item){return(item[0]=='setting_4');})[0][2])//returns 'blue'
//or using the labels provided by COLUMNS:
alert($.grep(json.DATA,
function(a){return(a[0]=='setting_4');})[0][$.inArray('COLOR',json.COLUMNS)])
You can do this with a simple for loop:
var obj = {"COLUMNS":["SETTING_NAME","SETTING_VALUE","COLOR"],
"DATA":[["setting_1",100.0,"yellow"],["setting_2",150.0,"red"],
["setting_3",30.0,"green"],["setting_4",11.0,"blue"]]};
for(var i = 0; i < obj.DATA.length; i++)
{
var row = obj.DATA[i]
if (row[0] == 'setting_4')
{
console.log(row[2]);
break;
}
}
Prints:
blue
You could simply reduce that list of DATA:
DATA.reduce(function (value, item) { if (item[0] === "setting_4") return item[2] })
You could wrap that whole thing into a function for easier use, passing in the "setting_4" part. E.g.
var getColour = function (id) {
return DATA.reduce(function (value, item) {
if (item[0] === id) return item[2]
})
}
UPDATE: you could zip the two lists together, perhaps that would make access easier?
obj['DATA'].map(function (row) {
return obj['COLUMNS'].reduce(function (memo, columnName, index) {
memo[columnName] = row[index]
return memo
}, {})
})
This will return something like the following:
[{
COLOR: "yellow",
SETTING_NAME: "setting_1",
SETTING_VALUE: 100
}]
A generic algorithm for translating the dataset into a more-easily-addressed structure.
var json = {
"COLUMNS": [
"SETTING_NAME",
"SETTING_VALUE",
"COLOR"],
"DATA": [
["setting_1",100.0,"yellow"],
["setting_2",150.0,"red"],
["setting_3",30.0,"green"],
["setting_4",11.0,"blue"]
]
};
function translateJSON(json) {
var oHash = {};
var data = json['DATA'];
var cols = json['COLUMNS'];
for(var i = 0, imax = data.length; i < imax; i++) {
var row = data[i]; // shorthand
for(var j = 1, jmax = cols.length; j < jmax; j++) {
var c = cols[j]; // shorthand
oHash[(row[0] + '_' + c.replace(/[^_]+_/, '')).toLowerCase()] = row[j];
}
}
return oHash;
}
var h = translateJSON(json);
console.log(h['setting_4_color']);
Edit: updated the code. translateJSON will transform the JSON into the data structure you described, for easier property access. If you anticipate needing to access more than one property from the same JSON payload, it will be much more efficient to do a one-time transform before data access than to use something like $.grep, and much less terse than doing the column-name cross-referencing by hand.
That said, I don't think the target data structure you asked for is necessarily the best one. Assuming you can't change the structure of the JSON payload, it would still probably be better to transform that into something like:
data = {
'setting_1': { 'value': 100.0, 'color': 'yellow' },
'setting_2': { 'value': 150.0, 'color': 'red' }
...
};