Append an object to a existing dictionary embedded in a json file.
I have a sample json file which I am reading using below code. Please check the code and sample json file here.
with open('sample.json') as fp:
dictObj = json.load(fp)
{
"versions" : [
{
"version" : "0.0",
"termsTranslations" : {
"en" : "my rev"
},
"createDate" : "2019-10-28T04:20:11.320Z"
}
]
"active" : "0.3",
"uiConfig" : {
"displayName" : "We've updated our terms",
"purpose" : "You must accept the updated terms in order to proceed.",
"buttonText" : "Accept"
}
}
I intend to add the below constructed object named newobj with value as below(has arabic text) to the sample.json file.
{'version': 0.4, 'termsTranslations': '{"ar": "<p dir="rtl"align="right">يرجى قراءة التعليم</p>","createDate": "2023-06-20T12:32:22Z"}'
The resultant sample.json file should like below:
{
"versions" : [
{
"version" : "0.0",
"termsTranslations" : {
"en" : "my rev"
},
"createDate" : "2019-10-28T04:20:11.320Z"
},
{'version': 0.4,
'termsTranslations': '{"ar": "<p dir="rtl"align="right">يرجى قراءة التعليمات الهامة التالية والشروط والأحكام قبل التسجيل في خدمة ساب نت والساب موبايل</p>',
'createDate': '2023-06-20T12:32:22Z'}
]
"active" : "0.3",
"uiConfig" : {
"displayName" : "We've updated our terms",
"purpose" : "You must accept the updated terms in order to proceed.",
"buttonText" : "Accept"
}
}
Is there a way this can be achieved in python using any of the library’s?
3
Answers
You’d simply append to the list
After reading the JSON file, you can just do the following:
Appending it would be:
I recommend you replace the double quote for
"
: The browsers will read them without problem. Specially if you need a valid JSON: JSON format does not accept APOSTROPHE instead of QUOTATION MARK (see).The final JSON, should look like this:
You also had a typo after the dictionary. There was no comma.