Created
January 24, 2025 19:33
-
-
Save JuanCaicedo/53e6a064e295f5fd28512e50d55e9412 to your computer and use it in GitHub Desktop.
AI prompt for generating flat json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Prompt | |
Could you write me a js program using lodash that will take a nested json structure like this | |
{ | |
"today": "Today", | |
"greeting": { | |
"morning": "1", | |
"evening": "2" | |
}, | |
"title": { | |
"morning": { | |
"test": "1" | |
} | |
} | |
} | |
and convert it to something like this | |
{ | |
"today": "Today", | |
"greeting.morning": "1", | |
"greeting.evening": "2", | |
"title.morning.test": "1" | |
} | |
# Response | |
Certainly! You can use lodash to achieve this by writing a function that recursively flattens the nested JSON structure. Here's a JavaScript program that does that: | |
```javascript | |
const _ = require('lodash'); | |
function flattenObject(obj, parentKey = '', result = {}) { | |
_.forOwn(obj, (value, key) => { | |
const newKey = parentKey ? `${parentKey}.${key}` : key; | |
if (_.isObject(value) && !_.isArray(value)) { | |
flattenObject(value, newKey, result); | |
} else { | |
result[newKey] = value; | |
} | |
}); | |
return result; | |
} | |
const nestedJson = { | |
"today": "Today", | |
"greeting": { | |
"morning": "1", | |
"evening": "2" | |
}, | |
"title": { | |
"morning": { | |
"test": "1" | |
} | |
} | |
}; | |
const flattenedJson = flattenObject(nestedJson); | |
console.log(flattenedJson); | |
``` | |
This program uses lodash's `_.forOwn` to iterate over the properties of the object. It checks if the value is an object and not an array, and if so, it recursively flattens it. Otherwise, it adds the key-value pair to the result object with the appropriate key. | |
When you run this program, it will output: | |
```json | |
{ | |
"today": "Today", | |
"greeting.morning": "1", | |
"greeting.evening": "2", | |
"title.morning.test": "1" | |
} | |
``` | |
This is the desired flattened JSON structure. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment