如何使用Python动态构建JSON对象?

时间:2014-04-16 13:06:53

标签: python json

我是Python新手,我正在玩JSON数据。我想通过向现有JSON对象添加一些键值来动态构建JSON对象。

我尝试了以下操作,但我得到了TypeError: 'str' object does not support item assignment

import json

json_data = json.dumps({})
json_data["key"] = "value"

print 'JSON: ', json_data

7 个答案:

答案 0 :(得分:425)

您构建对象之前将其编码为JSON字符串:

import json

data = {}
data['key'] = 'value'
json_data = json.dumps(data)

JSON是序列化格式,文本数据表示结构。它本身并不是那种结构。

答案 1 :(得分:18)

已经提供了一个解决方案,它允许构建字典(或嵌套字典以获取更复杂的数据),但是如果你想构建一个对象,那么也许可以尝试一下ObjDict'。这样可以更好地控制要创建的json,例如保留顺序,并允许构建为对象,这可能是您概念的首选表示。

先pip install objdict。

from objdict import ObjDict

data = ObjDict()
data.key = 'value'
json_data = data.dumps()

答案 2 :(得分:12)

您可以创建Python字典并将其序列化为一行中的JSON,它甚至都不丑。

my_json_string = json.dumps({'key1': val1, 'key2': val2})

答案 3 :(得分:8)

您可以使用IRibbonUIdoc

  

EasyDict允许将字典值作为属性访问(递归工作​​)。 python字典的类似Javascript的属性点表示法。

     

使用情况

EasyDict

[安装]:

  • >>> from easydict import EasyDict as edict >>> d = edict({'foo':3, 'bar':{'x':1, 'y':2}}) >>> d.foo 3 >>> d.bar.x 1 >>> d = edict(foo=3) >>> d.foo 3

答案 4 :(得分:3)

  • json.loads 以字符串作为输入并返回字典作为输出。
  • json.dumps 以字典作为输入并返回一个字符串作为输出。

如果您需要将 JSON 数据转换为 python 对象,它可以使用 Python3 完成,无需额外安装,使用 SimpleNamespaceobject_hook

来自字符串

import json
from types import SimpleNamespace

string = '{"foo":3, "bar":{"x":1, "y":2}}'

# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(string, object_hook=lambda d: SimpleNamespace(**d))

print(x.foo)
print(x.bar.x)
print(x.bar.y)

输出:

3
1
2

来自文件:

JSON 对象:data.json

{
    "foo": 3,
    "bar": {
        "x": 1,
        "y": 2
    }
}
import json
from types import SimpleNamespace

with open("data.json") as fh:
    string = fh.read()

# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(string, object_hook=lambda d: SimpleNamespace(**d))

print(x.foo)
print(x.bar.x)
print(x.bar.y)

输出:

3
1
2

来自请求

import json
from types import SimpleNamespace
import requests

r = requests.get('https://api.github.com/users/MilovanTomasevic')

# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(r.text, object_hook=lambda d: SimpleNamespace(**d))

print(x.name)
print(x.company)
print(x.blog)

输出:

Milovan Tomašević
NLB
milovantomasevic.com

要从 API 更美观、更快速地访问 JSON 响应,请查看 this response

答案 5 :(得分:2)

所有先前的答案都是正确的,这是一种更简单的方法。例如,创建一个Dict数据结构来序列化和反序列化一个对象

通知,在python中,Null不为Null,我有意使用它来演示如何存储null并将其转换为json null)

import json
print('serialization')
myDictObj = { "name":"John", "age":30, "car":None }
##convert object to json
serialized= json.dumps(myDictObj, sort_keys=True, indent=3)
print(serialized)
## now we are gonna convert json to object
deserialization=json.loads(serialized)
print(deserialization)

enter image description here

答案 6 :(得分:1)

我创建了一个递归函数来遍历表示 json 结构的嵌套字典。

  myjson={}
  myjson["Country"]= {"KR": { "id": "220", "name": "South Korea"}}
  myjson["Creative"]= {
                    "1067405": {
                        "id": "1067405",
                        "url": "https://cdn.gowadogo.com/559d1ba1-8d50-4c7f-b3f5-d80f918006e0.jpg"
                    },
                    "1067406": {
                        "id": "1067406",
                        "url": "https://cdn.gowadogo.com/3799a70d-339c-4ecb-bc1f-a959dde675b8.jpg"
                    },
                    "1067407": {
                        "id": "1067407",
                        "url": "https://cdn.gowadogo.com/180af6a5-251d-4aa9-9cd9-51b2fc77d0c6.jpg"
                    }
                }
   myjson["Offer"]= {
                    "advanced_targeting_enabled": "f",
                    "category_name": "E-commerce/ Shopping",
                    "click_lifespan": "168",
                    "conversion_cap": "50",
                    "currency": "USD",
                    "default_payout": "1.5"
                }

   json_data = json.dumps(myjson)

   #reverse back into a json

   paths=[]
   def walk_the_tree(inputDict,suffix=None):
       for key, value in inputDict.items():
            if isinstance(value, dict):
                if suffix==None:
                    suffix=key
                else:
                    suffix+=":"+key

                walk_the_tree(value,suffix)
            else:
                paths.append(suffix+":"+key+":"+value)
 walk_the_tree(myjson)
 print(paths)  

 #split and build your nested dictionary
 json_specs = {}
 for path in paths:
     parts=path.split(':')
     value=(parts[-1])
     d=json_specs
     for p in parts[:-1]:
         if p==parts[-2]:
             d = d.setdefault(p,value)
         else:
             d = d.setdefault(p,{})
    
 print(json_specs)        

 Paths:
 ['Country:KR:id:220', 'Country:KR:name:South Korea', 'Country:Creative:1067405:id:1067405', 'Country:Creative:1067405:url:https://cdn.gowadogo.com/559d1ba1-8d50-4c7f-b3f5-d80f918006e0.jpg', 'Country:Creative:1067405:1067406:id:1067406', 'Country:Creative:1067405:1067406:url:https://cdn.gowadogo.com/3799a70d-339c-4ecb-bc1f-a959dde675b8.jpg', 'Country:Creative:1067405:1067406:1067407:id:1067407', 'Country:Creative:1067405:1067406:1067407:url:https://cdn.gowadogo.com/180af6a5-251d-4aa9-9cd9-51b2fc77d0c6.jpg', 'Country:Creative:Offer:advanced_targeting_enabled:f', 'Country:Creative:Offer:category_name:E-commerce/ Shopping', 'Country:Creative:Offer:click_lifespan:168', 'Country:Creative:Offer:conversion_cap:50', 'Country:Creative:Offer:currency:USD', 'Country:Creative:Offer:default_payout:1.5']