简体   繁体   中英

Creating a JSON dynamically using Dictionary key value

I'm trying to generate a JSON file in the below format.

var highlighted_color = {
  mo: '#2980b9',
  fl: '#27ae60',
  or: '#8e44ad'
}

The Javascript code I have so far gone through each key-value pair grabs the data, I am however unable to understand how to process from here on.

Object.entries(data).forEach(([key, values]) => {
  var item = {}
  item[key] = values;
});

The key has the object and values has the color code

The following script will get you the required string (the keys are surrounded by double quotes, but otherwise it is exactly what you wanted):

 const data={ mo: '#2980b9', fl: '#27ae60', or: '#8e44ad' } let res="var highlighted_color = "+JSON.stringify(data,null,2); console.log(res);

To put this string into a file (on a server) you could send it to a PHP (or other) script on that server:

fetch('ScriptWillPutStringIntoFile.php?filename=colorData&str=var highlighted_color ='+res);

// the above works for SHORT bits of data (< 2014 bytes).
// For the general case you should use something like this:

var xhr = new XMLHttpRequest();
xhr.open("POST", 'ScriptWillPutStringIntoFile.php', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
    filename
    str: res
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM