I have a big JSON file that I want to intercept all the values that have the key text
associated with them, for example:
type":"doc",
"content":[
{
"type":"paragraph",
"content":[
{
"text":"this is a simple page, about a simple umbrella.",
"type":"text"
}
]
},
{
"type":"paragraph",
"content":[
{
"text":"you can use this text to find the umbrella page.",
"type":"text"
}
]
},
{
"type":"paragraph",
"content":[
{
"text":"do you like it?",
"type":"text"
}
]
},
I know I can use Object.keys
but that only covers the "top level" and doesn't go deeper.
I don't wish to use recursion for this, but use an iterative function.
I tried to use JSON.stringify
but it has poor performance:
const obj = JSON.parse(content);
let ret = '';
JSON.stringify(obj, (_, nested) => {
if (nested && nested[key]) {
ret = nested[key] '\n';
}
return nested;
});
CodePudding user response:
Not shure that I catch the question, but here is lodash solution:
const _ = require('lodash');
const data = '{"type":"doc","content":[{"type":"paragraph","content":[{"text":"this is a simple page, about a simple umbrella.","type":"text"}]},{"type":"paragraph","content":[{"text":"you can use this text to find the umbrella page.","type":"text"}]},{"type":"paragraph","content":[{"text":"do you like it?","type":"text"}]}]}';
const obj = JSON.parse(data);
const newObj = _.cloneDeepWith(obj, (val, key) => {
if (key === 'text') return `${val.toUpperCase()}`;
});
console.dir(newObj, {depth : null});
// type: 'doc',
// content: [
// {
// type: 'paragraph',
// content: [
// {
// text: 'THIS IS A SIMPLE PAGE, ABOUT A SIMPLE UMBRELLA.',
// type: 'text'
// }
// ]
// },
// {
// type: 'paragraph',
// content: [
// {
// text: 'YOU CAN USE THIS TEXT TO FIND THE UMBRELLA PAGE.',
// type: 'text'
// }
// ]
// },
// {
// type: 'paragraph',
// content: [ { text: 'DO YOU LIKE IT?', type: 'text' } ]
// }
// ]
// }
CodePudding user response:
If your goal is to just get the key text, you can use the following method.
var reg = /(?<=\")\w (?=\"\:)/g
var jsonValue = '{"glossary": {"title": "example glossary","GlossDiv": {"title": "S","GlossList": {"GlossEntry": {"ID": "SGML","SortAs": "SGML","GlossTerm": "Standard Generalized Markup Language","Acronym": "SGML","Abbrev": "ISO 8879:1986","GlossDef": {"para": "A meta-markup language, used to create markup languages such as DocBook.","GlossSeeAlso": ["GML", "XML"]},"GlossSee": "markup"}}}}}';
console.log(jsonValue.match(reg));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>