标签: simplejson

MongoDB对象序列化为JSON

我正在尝试在我的HTTP响应中发回一个JSON编码的MongoDB对象.我跟着其他几个类似的问题,但我仍然遗漏了一些东西.没有异常被抛出,但我<api.views.MongoEncoder object at 0x80a0c02c>在浏览器中得到了一个神秘的回应.我相信这很简单,但任何帮助都会受到赞赏.

功能:

from django.utils.simplejson import JSONEncoder
from pymongo.objectid import ObjectId

class MongoEncoder( JSONEncoder ):
     def _iterencode( self, o, markers = None ):
          if isinstance( o, ObjectId ):
               return """ObjectId("%s")""" % str(o)
          else:
               return JSONEncoder._iterencode(self, o, markers)
Run Code Online (Sandbox Code Playgroud)

views.py:

user = User({
    's_email': request.GET.get('s_email', ''),
    's_password': request.GET.get('s_password', ''),
    's_first_name': request.GET.get('s_first_name', ''),
    's_last_name': request.GET.get('s_last_name', ''),
    'd_birthdate': request.GET.get('d_birthdate', ''),
    's_gender': request.GET.get('s_gender', ''),
    's_city': request.GET.get('s_city', ''),
    's_state': request.GET.get('s_state', ''),
})

response = {
    's_status': 'success',
    'data': user
}
return HttpResponse(MongoEncoder( …
Run Code Online (Sandbox Code Playgroud)

django simplejson mongodb pymongo

6
推荐指数
1
解决办法
8747
查看次数

django escapejs和simplejson

我正在尝试使用simplejson.dumps将Python数组编码为json:

In [30]: s1 = ['test', '<script>']

In [31]: simplejson.dumps(s1)
Out[31]: '["test", "<script>"]'
Run Code Online (Sandbox Code Playgroud)

工作良好.

但是我想在调用simplejson.dumps之前首先逃避字符串(使用Django中的escapejs):

In [35]: s_esc
Out[35]: [u'test', u'\\u003Cscript\\u003E']

In [36]: print simplejson.dumps(s_esc)
["test", "\\u003Cscript\\u003E"]
Run Code Online (Sandbox Code Playgroud)

我的问题是:我希望转义的字符串是:["test", "\u003Cscript\u003E"]而不是["test", "\\u003Cscript\\u003E"]

我可以用replace:

In [37]: print simplejson.dumps(s_esc).replace('\\\\', '\\')
["test", "\u003Cscript\u003E"]
Run Code Online (Sandbox Code Playgroud)

但这是一个好方法吗?我只想在将它们编码为json之前首先转义字符串.因此,当我在模板中使用它们时,不会出现语法错误.

谢谢.:)

django json escaping simplejson

6
推荐指数
1
解决办法
3415
查看次数

Google Data Source JSON无效?

我正在使用他们的Python库实现Google数据源.我希望库中的响应能够使用simplejson库在另一个Python脚本中导入.

但是,即使他们的示例也没有在JSONLint中验证:

{cols:
    [{id:'name',label:'Name',type:'string'},
     {id:'salary',label:'Salary',type:'number'},
     {id:'full_time',label:'Full Time Employee',type:'boolean'}],
rows:
    [{c:[{v:'Jim'},{v:800,f:'$800'},{v:false}]},
     {c:[{v:'Bob'},{v:7000,f:'$7,000'},{v:true}]},
     {c:[{v:'Mike'},{v:10000,f:'$10,000'},{v:true}]},
     {c:[{v:'Alice'},{v:12500,f:'$12,500'},{v:true}]}]}
Run Code Online (Sandbox Code Playgroud)

如何调整simplejson'loads'函数来导入上面的JSON?我认为主要问题是对象键不是字符串.

我宁愿不写一个正则表达式来将键转换为字符串,因为我认为这样的代码会很难维护.

我正在尝试使用simplejson将上面的json导入到python中时出现"Expecting property name:line 1 column 1(char 1)"错误.

python simplejson

5
推荐指数
1
解决办法
2031
查看次数

在Python中解码复杂的JSON

我有一个用PHP创建的JSON对象,JSON对象在其中一个单元格中包含另一个转义的JSON字符串:

php > $insidejson = array('foo' => 'bar','foo1' => 'bar1');
php > $arr = array('a' => array('a1'=>json_encode($insidejson)));
php > echo json_encode($arr);
{"a":{"a1":"{\"foo\":\"bar\",\"foo1\":\"bar1\"}"}}

然后,使用Python,我尝试使用simplejson进行deocding:

>>> import simplejson as json
>>> json.loads('{"a":{"a1":"{\"foo\":\"bar\",\"foo1\":\"bar1\"}"}}')

此操作失败,并显示以下错误:

Traceback (most recent call last):
  File "", line 1, in ?
  File "build/bdist.linux-i686/egg/simplejson/__init__.py", line 307, in loads
  File "build/bdist.linux-i686/egg/simplejson/decoder.py", line 335, in decode
  File "build/bdist.linux-i686/egg/simplejson/decoder.py", line 351, in raw_decode
ValueError: Expecting , delimiter: line 1 column 14 (char 14)

如何在Python中解码此JSON对象?PHP和JS都成功解码它,我无法改变它的结构,因为这需要在不同语言的许多不同组件中进行重大更改.

谢谢!

php python json simplejson

5
推荐指数
1
解决办法
6315
查看次数

使用Python simplejson返回预生成的json

我有一个GeoDjango模型对象,我不想序列化为json.我在我看来这样做:

lat = float(request.GET.get('lat'))
lng = float(request.GET.get('lng'))
a = Authority.objects.get(area__contains=Point(lng, lat))
if a:
    return HttpResponse(simplejson.dumps({'name': a.name, 
                                          'area': a.area.geojson,
                                          'id': a.id}), 
                        mimetype='application/json')
Run Code Online (Sandbox Code Playgroud)

问题是,simplejson认为a.area.geojson作为一个简单的字符串,即使它是美丽的预先生成的JSON.这可以通过eval()"区域字符串" 在客户端中轻松修复,但我想做到这一点.我可以告诉simplejson一个特定的字符串已经是json并且应该按原样使用(而不是作为简单的字符串返回)?或者还有另一种解决方法吗?

更新 只是为了澄清,这是当前返回的json:

{
    "id": 95,
    "name": "Roskilde",
    "area": "{ \"type\": \"MultiPolygon\", \"coordinates\": [ [ [ [ 12.078701, 55.649927 ], ... ] ] ] }"
}
Run Code Online (Sandbox Code Playgroud)

挑战是让"area"成为json字典而不是简单的字符串.

python django json simplejson geodjango

5
推荐指数
2
解决办法
1086
查看次数

XML库类似于simplejson/json? - Python

是否有类似于simplejson的库,它可以实现与XML的快速序列化数据.

e.g. json.loads('{vol:'III', title:'Magical Unicorn'}')

e.g. json.dumps([1,2,3,4,5])
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

python xml json simplejson

5
推荐指数
1
解决办法
3075
查看次数

如何从Python中的JSON对象中提取数据?

我试图从api调用api.trends()[Tweepy]返回的JSON对象中提取数据,但我无法提取数据.

任何人都可以给我一个如何从JSON对象中提取数据的示例.我想以表格形式提取数据.

提前致谢.

python json simplejson tweepy

5
推荐指数
1
解决办法
2万
查看次数

pylint报告通过simplejson加载的数据可能没有成员错误

当我用pylint运行以下代码块时,我没有错误.

import json
for key, value in json.loads('{"foo":"bar"}').items():
    print(key, value)
Run Code Online (Sandbox Code Playgroud)

当切换出jsonsimplejson,然后运行pylint的,我得到的错误:

Instance of 'bool' has no 'items' member (but some types could not be inferred) (maybe-no-member)
Run Code Online (Sandbox Code Playgroud)

从比较astroidsimplejson.loads和json.loads的推测结果看来,即使json和simplejson都是用c_speedups编译的,astroid 在处理库时会选择scan_once函数的python版本simplejson,而c处理json库时的版本.

import astroid.builder
builder = astroid.builder.AstroidBuilder()
ast = builder.string_build("""
import simplejson
import json
x = json.loads('"test"')
y = simplejson.loads('"test"')
""")

json_assignment, simplejson_assignment = list(ast.get_children())[2:]
print "json:", list(json_assignment.get_children())[-1].infered()
print "simplejson:", list(simplejson_assignment.get_children())[-1].infered()
Run Code Online (Sandbox Code Playgroud)

运行上面的代码输出:

json: [YES]
simplejson: [YES, <Const(NoneType) l.97 [simplejson.scanner] at Ox102720290>, <Const(bool) …
Run Code Online (Sandbox Code Playgroud)

python pylint simplejson

5
推荐指数
1
解决办法
1024
查看次数

java.lang.String无法强制转换为org.json.simple.JSONObject simple-json

尝试使用google的simple-json解析一个简单的json时,我遇到了奇怪的问题.

这是我的代码不起作用:

String s = args[0].toString();
JSONObject json = (JSONObject)new JSONParser().parse(s);
Run Code Online (Sandbox Code Playgroud)

当我执行时,它会给我例外 java.lang.String cannot be cast to org.json.simple.JSONObject

但是,当我直接硬编码json时,它的工作正常.扫管笏可能是什么原因?

JSONObject json = (JSONObject)new JSONParser().parse("{\"application\":\"admin\",\"keytype\":\"PRODUCTION\",\"callbackUrl\":\"qwerewqr;ewqrwerq;qwerqwerq\",\"authorizedDomains\":\"ALL\",\"validityTime\":\"3600000\",\"retryAfterFailure\":true}");
Run Code Online (Sandbox Code Playgroud)

UPDATE

当我打印s时,它会给我输出如下:

"{\"application\":\"admin\",\"keytype\":\"PRODUCTION\",\"callbackUrl\":\"qwerewqr;ewqrwerq;qwerqwerq\",\"authorizedDomains\":\"ALL\",\"validityTime\":\"3600000\",\"retryAfterFailure\":true}"
Run Code Online (Sandbox Code Playgroud)

java json simplejson

5
推荐指数
1
解决办法
4万
查看次数

JSONObject 的 URL 问题

我有以下代码,但是当我在数据库中保存以下 JSON 时,它给了我错误的 url,例如{"#url#":"https:\/\/www.test.com\/test"}

import org.json.simple.JSONObject;

public class DemoURL {
    private static String url = "https://www.test.com/test";
    public static void main(String[] args) {
        JSONObject msgJson = new JSONObject();
        msgJson.put("#url#", url);
        System.out.println(msgJson.toString());
    }
}
Run Code Online (Sandbox Code Playgroud)

我想要像这样的网址{"#url#":"https://www.test.com/test"} 请建议如何修复它?

java json simplejson

5
推荐指数
1
解决办法
2140
查看次数

标签 统计

simplejson ×10

json ×7

python ×6

django ×3

java ×2

escaping ×1

geodjango ×1

mongodb ×1

php ×1

pylint ×1

pymongo ×1

tweepy ×1

xml ×1