Home > Software design >  Convert key value object to json - javascript
Convert key value object to json - javascript

Time:02-17

Hey All I have this object that I try to convert to json. I tried

reportDropDownsJson2 =  JSON.parse('{"'   reportDropDownsJson.replace(/&/g, '","').replace(/=/g,'":"')   '"}', function(key, value) { return key===""?value:decodeURIComponent(value) });
            reportDropDownsJson['downloadcsv'] = true; 

and the result is:

TypeError: reportDropDownsJson.replace is not a function

this is the object (called reportDropDownsJson) that I try to convert to json

ad_type: ""
agency_id[]: ""
auction_type: ""
brand_id[]: ""
campaign: ""
campaign-drop: ""
column_filter[]: (23) ['Timestamp', 'Date', 'Hour', 'Brand', 'Requests', 'Bids', 'Bid %', 'Wins', 'Win %', 'Fill %', 'Imps Pixel', 'Revenue $', 'Cost $', 'eCPM', 'Sales Person', 'AdOPS Person', 'Account Manager Person', 'IVT Provider 1', 'Viewability Provider 1', 'VCR', 'CTR', 'VTR', 'Campaign']
deal_id[]: ""
deal_personnel[]: ""
deal_type[]: ""
device_type: ""
dsp_id[]: ""
edit_saved_report: ""
end_date: "2022-02-16"
frozen_filter[]: "Timestamp"
group_by[]: ""
interval: "hourly"
media_type: ""
office_country[]: "All"
pub_id[]: ""
ssp_id[]: ""
start_date: "2022-02-16"
timezone: "US/Eastern"
_token: "Fixv8PZsW6vsavjysdbVcxDsedqy8tiw7s7vUVBp"

CodePudding user response:

We cant use replace on objects.It can be used on strings.If you want to replace the values of object you can loop through object and use replace on single values.

Yoc can try this method to get values of an object:

for (const [key, value] of Object.entries(reportDropDownsJson)) {
  console.log(`${key}: ${value}`);
}

Inside for loop you can use value.replace() and do whatever logic

CodePudding user response:

The "Convert Keys/Values into Objects" transformation extracts key-value pairs from a source column and writes them into a new column. The generated column has a datatype of "Object".

An object stores information in a key-value pair, where the key is a string and the value is the corresponding value for that record.

CodePudding user response:

Replace cannot be used in objects.

To iterate the keys and values inside an object, you can do this:

Object.entries(reportDropDownsJson).forEach(([key, value]) => {
    // Do whatever you need to write out the json with the "key" and "value" pair
});
  • Related