如何在JSON对象中存储JSON字符串而不会导致语法错误?

时间:2017-06-01 13:48:02

标签: javascript python json

我有一个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对象吗?

2 个答案:

答案 0 :(得分:2)

这适用于使用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"}'

快乐的编码!!!

答案 1 :(得分:1)

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)