如何在JSON对象中存储JSON字符串而不引起语法错误?

2024-09-29 23:23:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个JSON对象,在resource_hours字段中我想存储一个JSON字符串

{
  "id": 4,
  "resource": 1,
  "resource_hours": "json goes here",
  "start": "2009-10-10",
  "end": "2010-10-10",
  "created_at": "2017-06-01T13:23:06.103867Z",
  "modified_at": "2017-06-01T13:23:06.103867Z"
}

下面是我要存储的字符串/对象:

{
  "winner": "john",
  "loser": "not john"
}

我试过这个:

"resource_hours": "{"winner":"john","loser":"not john"}"

但很明显,由于双引号重叠,这就产生了一个错误

我还尝试使用\来转义引号,如下所示:

"resource_hours": "{\"winner\":\"john\",\"loser\":\"not john\"}"

这是有效的(没有引发错误),但它仍然是一个JSON字符串/对象吗?如果使用API从数据库中提取,它仍然可以被解析为JSON对象吗


Tags: 对象字符串idjsonhere错误notjohn
2条回答

JSON.stringify方法允许您将对象转换为字符串:

const objectWillBeStoredInJson = {
  "winner": "john",
  "loser": "not john"
}

const object = {
  "id": 4,
  "resource": 1,
  "resource_hours": JSON.stringify(objectWillBeStoredInJson),
  "start": "2009-10-10",
  "end": "2010-10-10",
  "created_at": "2017-06-01T13:23:06.103867Z",
  "modified_at": "2017-06-01T13:23:06.103867Z"
}

现在,object.resource_hours有一个字符串,在解析时引用objectWillBeStoredInJson

您可以使用JSON.parse来访问它:

const objectWillBeStoredInJson = JSON.parse(object.resource_hours)

这将适用于使用Python的用户:

>>> import json
>>> j = {
... "id": 4,
... "resource": 1,
... "resource_hours": "json goes here",
... "start": "2009-10-10",
... "end": "2010-10-10",
... "created_at": "2017-06-01T13:23:06.103867Z",
... "modified_at": "2017-06-01T13:23:06.103867Z"
... }
>>> j
{'id': 4, 'resource': 1, 'resource_hours': 'json goes here', 'start': '2009-10-10', 'end': '2010-10-10', 'created_at': '
2017-06-01T13:23:06.103867Z', 'modified_at': '2017-06-01T13:23:06.103867Z'}

>>> # converting your data to json
>>> act_json = json.dumps(j)
>>> act_json
'{"id": 4, "resource": 1, "resource_hours": "json goes here", "start": "2009-10-10", "end": "2010-10-10", "created_at":
"2017-06-01T13:23:06.103867Z", "modified_at": "2017-06-01T13:23:06.103867Z"}'

>>> # value that needs to be added
>>> val_to_store = {
... "winner": "john",
... "loser": "not john"
... }

>>> # getting the data and converting it to dictionary
>>> j = json.loads(act_json)

>>> # assigning the values
>>> j['resource_hours'] = val_to_store
>>> j
{'id': 4, 'resource': 1, 'resource_hours': {'winner': 'john', 'loser': 'not john'}, 'start': '2009-10-10', 'end': '2010-
10-10', 'created_at': '2017-06-01T13:23:06.103867Z', 'modified_at': '2017-06-01T13:23:06.103867Z'}

>>> # converting back to json, if needed
>>> to_json = json.dumps(j)
>>> to_json
'{"id": 4, "resource": 1, "resource_hours": {"winner": "john", "loser": "not john"}, "start": "2009-10-10", "end": "2010
-10-10", "created_at": "2017-06-01T13:23:06.103867Z", "modified_at": "2017-06-01T13:23:06.103867Z"}'

快乐编码

相关问题 更多 >

    热门问题