0

I have a use case where i will initially have a JSON object with few elements and I want to add few more new elements to this object using JSON path with the help of Javascript.

Eg:

JSON object:

{ "article": { "title": "Article Title", "sect1": { "title": "Section1 Title", "para": "Text" } } }

I would like to set 'article.sect1.subsection.subtitle' as 'Test Title' and 'article.sect1.subsection.para' as 'Number'.

Could you please suggest any solution?

I could add element inside existing section as below JSONObject.article.sect1.sect1.newElement = 'newelementvalue';

But this is not working for above scenario.

PRAI
  • 1

1 Answers1

0

You can easily convert the string to a JSON object and then manipulate it as you would normally. Once you are done, stringify it back and you can persist it how you wish.

const json = `{ "article": { "title": "Article Title", "sect1": { "title": "Section1 Title", "para": "Text" } } }`;
const obj = JSON.parse(json);
obj.article.sect1.subtitle = 'Test Title';
obj.article.sect1.subsection = {para: 'Number'};
const str = JSON.stringify(obj);

console.log(str)
Krzysztof Krzeszewski
  • 5,912
  • 2
  • 17
  • 30
KiaiFighter
  • 647
  • 5
  • 18