【问题标题】:load data in exact order from json string(python, django)从 json 字符串(python,django)按确切顺序加载数据
【发布时间】:2016-07-20 09:28:36
【问题描述】:

我有来自 ajax、jquery 的 json 数据,如下所示

json_data_from_ajax = u'{"1_sd":{"name":"unicode","data_type_choices":"Unicode"},"2_sd":{"name":"unicode_secret","data_type_choices":"Unicode"},"3_sd":{"name":"unicode_mandatory","data_type_choices":"Unicode"},"4_sd":{"name":"boolean","data_type_choices":"Unicode"},"5_sd":{"name":"boolean_secret","data_type_choices":"Unicode"},"6_sd":{"name":"boolean_mandatory","data_type_choices":"Unicode"},"7_sd":{"name":"integer","data_type_choices":"Unicode"},"8_sd":{"name":"integer_value","data_type_choices":"Unicode"},"9_sd":{"name":"integer_mandatory","data_type_choices":"Unicode"}}'

我正在尝试加载(将json字符串转换为实际数据)上述数据如下

将 json 导入为 simplejson settings_records = simplejson.loads(json_data_from_ajax) 打印 settings_records

输出

{u'8_sd': {u'data_type_choices': u'Unicode'}, u'3_sd': {u'name': u'unicode_mandatory', u'data_type_choices': u'Unicode'}, u'1_sd': {u'name': u'unicode', u'data_type_choices': u'Unicode'}, u'6_sd': {u'name': u'boolean_mandatory', u'data_type_choices': u'Unicode'}, u'9_sd': {u'name': u'integer_mandatory', u'data_type_choices': u'Unicode'}, u'4_sd': {u'name': u'boolean', u'data_type_choices': u'Unicode'}, u'7_sd': {u'name': u'integer', u'data_type_choices': u'Unicode'}, u'2_sd': {u'name': u'unicode_secret', u'data_type_choices': u'Unicode'}, u'5_sd': {u'name': u'boolean_secret', u'data_type_choices': u'Unicode'}}

所以从上面的输出中你可以看到字典中的键是随机排序的,比如u'8_sd', u'3_sd', u'1_sd'......,但我需要它们,因为它来自我从 ajax 收到的 json 字符串,比如"1_sd", "2_sd", "3_sd", "4_sd"......

那么我们怎样才能按顺序加载json字符串呢?

【问题讨论】:

  • 您不能对对象的属性进行排序。如果您需要以特定顺序遍历集合,则需要更改 JSON 以返回对象数组
  • 类似地,Python dict 是无序的。但是,在将 Python 数据结构转储到 JSON 时,您可以指定 sort_keys=True 以获取每个字典中的键以按字典顺序发出。

标签: jquery python json ajax django


【解决方案1】:

这可能会有所帮助(不适用于 python

import simplejson as json
from collections import OrderedDict

settings_records = json.loads(json_data_from_ajax, object_pairs_hook=OrderedDict)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 2013-10-15
    • 2023-03-20
    • 2019-11-04
    • 1970-01-01
    • 2013-10-03
    • 2018-09-17
    相关资源
    最近更新 更多