0

yeah. (sorry my bad english T_T)

{
  "BlockA": {
    "BlockB": {
      "name": "BlockB",
      "value": "Value_B"
    }
}

this is just my simple json file.

and, i need to change this for

{
  "BlockA": {
    "BlockB": {
      "name": "BlockB",
      "value": "Value_B"
    },
    "BlockC": {
      "name": "BlockC",
      "value": "Value_C"
    }
}

like this, i tried append, json.loads, json.load, json.dumps, json.dump.. but all functions gave me error.

i tried,

import json
f = open(".\simple.json", "r")
json_obj = json.load(f)

#json_obj.append << doesnt work
#json_obj.dump("blahblah", Ensureblahblah=False) << doesnt work too.

using python version 3.4.1

2
  • What is the exact error Commented May 19, 2014 at 14:09
  • Above written json is invalid too. Commented May 19, 2014 at 14:25

2 Answers 2

4

JSON is just a way to serialize data. If you parse a JSON object, you'll get a python dictionary. If you parse a JSON array, you'll get a python list. If you parse a string, you get a string... etc.

So, if you parse a JS object, you'll get a dictionary. Dictionaries don't have append or dump methods.

This means:

import json
f = open(".\simple.json", "r")
json_obj = json.load(f)  # <--- this is a dictionary!

json_obj['BlockC'] = {'name': '...', 'value': '...'}

And then dump it back to the file (read the json API if you have doubts)

Sign up to request clarification or add additional context in comments.

2 Comments

sorry for cant choose you,
Well, I offered an explanation and you were asking for a solution for your homework.
1

Here is a code guided explanation

import json

open_file_object = open("/home/action/workspace/playkt/data.json", 'r')
decoded_json = json.load(open_file_object)

print (decoded_json)

"""
{
  "BlockA": {
    "BlockB": {
      "name": "BlockB",
      "value": "Value_B"
    }
  }
}
"""

decoded_json["BlockA"]["BlockC"] = { "name": "BlockC", "value": "Value_C" }

print(decoded_json)

"""
{
    "BlockA": {
        "BlockB": {
            "name": "BlockB",
            "value": "Value_B"
        },
        "BlockC": {
            "name": "BlockC",
            "value": "Value_C"
        }
    }
}
"""

#write to file 
output_file = "/home/action/workspace/playkt/data.json"

with open(output_file, 'w') as write_file_object:
  #Serialize dictionary to a JSON formatted string and write to file
  write_file_object.write(json.dumps(decoded_json))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.