16

I have two JSON objects. One is python array which is converted using json,dumps() and other contains records from database and is serialized using json serializer. I want to combine them into a single JSON object.

For eg:

obj1 = ["a1", "a2", "a3"]

obj2 = [{
    "pk": "e1",
    "model": "AB.abc",
    "fields": {
      "e_desc": "abcd"
    }
  },
  {
    "pk": "e1",
    "model": "AB.abc",
    "fields": {
      "e_desc": "hij"
    }
  }
]

I want to merge them into single object as below:

finalObj = {
  obj1: ["a1", "a2", "a3"],
  obj2: [{
      "pk": "e1",
      "model": "AB.abc",
      "fields": {
        "e_desc": "abcd"
      }
    },
    {
      "pk": "e1",
      "model": "AB.abc",
      "fields": {
        "e_desc": "hij"
      }
    }
  ]
}

How can i do this?

1
  • typeof(finalObj.obj2) back on the client is string. To get back the JSON object use JSON.parse(finalObj) Commented Jan 23, 2015 at 17:34

3 Answers 3

23

You can't do it once they're in JSON format - JSON is just text. You need to combine them in Python first:

data = { 'obj1' : obj1, 'obj2' : obj2 }
json.dumps(data)
Sign up to request clarification or add additional context in comments.

Comments

6

Not sure if I'm missing something, but I think this works (tested in python 2.5) with the output you specify:

import simplejson

finalObj = { 'obj1': obj1, 'obj2': obj2 }
simplejson.dumps(finalObj)

Comments

0

You have two techniques. The list version suffers from the limitation that the order matters. However, the JSON is slightly simpler-looking. The dictionary version has nested data, which looks more complex.

data = { 'obj1' : obj1, 'obj2' : obj2 }
json.dumps(data,indent=2)


data = [ obj1, obj2 ]
json.dumps(data,indent=2)

2 Comments

Thanks. Why do you add indent=2?
The indent parameter specifies the spaces that are used at the beginning of a line. We can use the indent parameter of json - pynative.com/python-prettyprint-json-data

Your Answer

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