如何在postgres列中存储json值

时间:2019-07-18 07:35:42

标签: json postgresql

我有一个包含两列的表,其中一列应存储 int ,另一列应存储 json

我要在表中存储的数据。

id,polygon
1,"{""type"": ""Feature"",
    ""properties"": {
        ""stroke"": ""#555555"",
        ""stroke-width"": 2,
        ""stroke-opacity"": 1,
        ""fill"": ""#00aa22"",
        ""fill-opacity"": 0.5
    },
    ""geometry"": {
        ""type"": ""Polygon"",
        ""coordinates"": [
            [
                [-76.97021484375,
                    40.17887331434696
                ],
                [-74.02587890625,
                    39.842286020743394
                ],
                [-73.4326171875,
                    41.713930073371294
                ],
                [-76.79443359375,
                    41.94314874732696
                ],
                [-76.97021484375,
                    40.17887331434696
                ]
            ]
        ]
    }
}"

我讨厌按以下方式存储在postgres中:

insert into gjl_polygon values(1,'"{""type"": 
""Feature"",""properties"": {""stroke"": ""#555555"",""stroke- 
width"": 2,""stroke-opacity"": 1,""fill"": ""#00aa22"",""fill- 
opacity"": 0.5},""geometry"": {""type"": 
""Polygon"",""coordinates"": 
[[[-76.97021484375,40.17887331434696],[-74.02587890625, 
39.842286020743394 ],[-73.4326171875, 41.713930073371294], 
[-76.79443359375,41.94314874732696], 
[-76.97021484375,40.17887331434696]]]}}"');

我遇到以下错误,

Expecting ':' delimiter: line 1 column 4 (char 3)

1 个答案:

答案 0 :(得分:1)

您的代码的问题是两次使用双引号引起来。尝试这样编辑:

{
    "type": "Feature",
    "properties": {
        "stroke": "#555555",
        "stroke-width": 2,
        "stroke-opacity": 1,
        "fill": "#00aa22",
        "fill-opacity": 0.5
    },
    "geometry": {
        "type": "Polygon",
        "coordinates": [
            [
                [-76.97021484375,
                    40.17887331434696
                ],
                [-74.02587890625,
                    39.842286020743394
                ],
                [-73.4326171875,
                    41.713930073371294
                ],
                [-76.79443359375,
                    41.94314874732696
                ],
                [-76.97021484375,
                    40.17887331434696
                ]
            ]
        ]
    }
}

上面的JSON是有效的JSON字符串,应该可以正常工作。