1

I'm sure this is simple but my heads not with it today, I'm trying to output a JSON file in this format:

{"A": {"B": [1, 1, 1, 1, 1, 1]}}

My code so far is:

jsonobj = {"A":{"B":[]
                      },
           }
var1 = 1
jsonobj["A"]["B"].append(dict(f=var1))
with open('data.json', 'w') as f:
    json.dump(jsonobj, f)
print jsonobj

As you can guess its a mismatch of code from StackOverflow and outputting wrong,

{'A': {'B': [{'f': 1}]}}

Sure it's an easy one, Thanks in advance.

1
  • Why can't you do jsonobj = {"A": {"B": [1, 1, 1, 1, 1, 1]}}, what's the dynamic part? Commented May 19, 2017 at 11:32

1 Answer 1

1

You need to do

jsonobj["A"]["B"].append(var1)

If it is like

var1 = [1,1,1,1]
jsonobj["A"]["B"].extend(var1)
Sign up to request clarification or add additional context in comments.

1 Comment

This does not produce {"A": [{"B": [1, 1, 1, 1, 1, 1]}]} though which OP said was the desired result.

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.