根据指定键对自定义 JSON 输出

news2024/10/23 22:05:34

要根据指定键对自定义 JSON 进行输出,通常的做法是:

  1. 解析 JSON 数据。
  2. 按照用户给定的键提取或排序数据。
  3. 重新构造并输出 JSON 数据。

这里有几个常见的场景:

  • 提取特定键及其值。
  • 按特定键排序 JSON 数组。
  • 过滤掉不需要的键。

接下来,我们将用 Python 演示这些操作,结合 json 模块解析和处理 JSON 数据。

在这里插入图片描述

问题背景

在使用 simplejson 库将 Python 字典转换为 JSON 时,希望为某些特定的键对自定义输出。例如,需要 callbackscope 这两个键的值不包含双引号,以便 JavaScript 能够解析数据,而不是将其视为字符串。

解决方案

方法一:修改 JSON 源代码

  1. 导入必要的模块。
import json
from json.encoder import encode_basestring_ascii, encode_basestring, FLOAT_REPR, INFINITY, c_make_encoder
  1. 创建自定义键类 JsonSpecialKey
class JsonSpecialKey(object):
    def __init__(self, data):
        self.data = data
  1. 创建自定义 JSON 编码器 JsonSpecialEncoder
class JsonSpecialEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, JsonSpecialKey):
            return obj.data
        return json.JSONEncoder.default(self, obj)
  1. 使用自定义编码器对数据进行编码。
d = {'testKey': JsonSpecialKey('function() {alert(123);}')}
print(json.dumps(d, cls=JsonSpecialEncoder, ensure_ascii=False, indent=4))

方法二:使用预定义的 JSON 编码器

一些 JSON 编码器库提供了更简单的自定义输出方式。例如,ujson 库允许您通过添加 @ 符号来指定需要排除双引号的键。

  1. 安装 ujson 库。
pip install ujson
  1. 导入必要的模块。
import ujson
  1. 使用自定义编码器对数据进行编码。
d = {'testKey': 'function() {alert(123);}'}
print(ujson.dumps(d, double_quote=False, escape_forward_slashes=False))

代码示例

# 方法一:修改 JSON 源代码
import json
from json.encoder import encode_basestring_ascii, encode_basestring, FLOAT_REPR, INFINITY, c_make_encoder

class JsonSpecialKey(object):
    def __init__(self, data):
        self.data = data

def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,
        _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot,
        ## HACK: hand-optimized bytecode; turn globals into locals
        ValueError=ValueError,
        dict=dict,
        float=float,
        id=id,
        int=int,
        isinstance=isinstance,
        list=list,
        str=str,
        tuple=tuple,
    ):

    if _indent is not None and not isinstance(_indent, str):
        _indent = ' ' * _indent

    def _iterencode_list(lst, _current_indent_level):
        if not lst:
            yield '[]'
            return
        if markers is not None:
            markerid = id(lst)
            if markerid in markers:
                raise ValueError("Circular reference detected")
            markers[markerid] = lst
        buf = '['
        if _indent is not None:
            _current_indent_level += 1
            newline_indent = '\n' + _indent * _current_indent_level
            separator = _item_separator + newline_indent
            buf += newline_indent
        else:
            newline_indent = None
            separator = _item_separator
        first = True
        for value in lst:
            if first:
                first = False
            else:
                buf = separator
            if isinstance(value, str):
                yield buf + _encoder(value)
            elif value is None:
                yield buf + 'null'
            elif value is True:
                yield buf + 'true'
            elif value is False:
                yield buf + 'false'
            elif isinstance(value, int):
                yield buf + str(value)
            elif isinstance(value, float):
                yield buf + _floatstr(value)
            elif isinstance(value, JsonSpecialKey):
                yield buf + value.data

            else:
                yield buf
                if isinstance(value, (list, tuple)):
                    chunks = _iterencode_list(value, _current_indent_level)
                elif isinstance(value, dict):
                    chunks = _iterencode_dict(value, _current_indent_level)
                else:
                    chunks = _iterencode(value, _current_indent_level)
                for chunk in chunks:
                    yield chunk
        if newline_indent is not None:
            _current_indent_level -= 1
            yield '\n' + _indent * _current_indent_level
        yield ']'
        if markers is not None:
            del markers[markerid]

    def _iterencode_dict(dct, _current_indent_level):
        if not dct:
            yield '{}'
            return
        if markers is not None:
            markerid = id(dct)
            if markerid in markers:
                raise ValueError("Circular reference detected")
            markers[markerid] = dct
        yield '{'
        if _indent is not None:
            _current_indent_level += 1
            newline_indent = '\n' + _indent * _current_indent_level
            item_separator = _item_separator + newline_indent
            yield newline_indent
        else:
            newline_indent = None
            item_separator = _item_separator
        first = True
        if _sort_keys:
            items = sorted(dct.items(), key=lambda kv: kv[0])
        else:
            items = dct.items()
        for key, value in items:
            if isinstance(key, str):
                pass
            # JavaScript is weakly typed for these, so it makes sense to
            # also allow them.  Many encoders seem to do something like this.
            elif isinstance(key, float):
                key = _floatstr(key)
            elif key is True:
                key = 'true'
            elif key is False:
                key = 'false'
            elif key is None:
                key = 'null'
            elif isinstance(key, int):
                key = str(key)
            elif _skipkeys:
                continue
            else:
                raise TypeError("key " + repr(key) + " is not a string")
            if first:
                first = False
            else:
                yield item_separator
            yield _encoder(key)
            yield _key_separator
            if isinstance(value, str):
                yield _encoder(value)
            elif value is None:
                yield 'null'
            elif value is True:
                yield 'true'
            elif value is False:
                yield 'false'
            elif isinstance(value, int):
                yield str(value)
            elif isinstance(value, float):
                yield _floatstr(value)
            elif isinstance(value, JsonSpecialKey):
                yield value.data
            else:
                if isinstance(value, (list, tuple)):
                    chunks = _iterencode_list(value, _current_indent_level)
                elif isinstance(value, dict):
                    chunks = _iterencode_dict(value, _current_indent_level)
                else:
                    chunks = _iterencode(value, _current_indent_level)
                for chunk in chunks:
                    yield chunk
        if newline_indent is not None:
            _current_indent_level -= 1
            yield '\n' + _indent * _current_indent_level
        yield '}'
        if markers is not None:
            del markers[markerid]

    def _iterencode(o, _current_indent_level):
        if isinstance(o, str):
            yield _encoder(o)
        elif o is None:
            yield 'null'
        elif o is True:
            yield 'true'
        elif o is False:
            yield 'false'
        elif isinstance(o, int):
            yield str(o)
        elif isinstance(o, float):
            yield _floatstr(o)
        elif isinstance(o, JsonSpecialKey):
            yield o.data
        elif isinstance(o, (list, tuple)):
            for chunk in _iterencode_list(o, _current_indent_level):
                yield chunk
        elif isinstance(o, dict):
            for chunk in _iterencode_dict(o, _current_indent_level):
                yield chunk
        else:
            if markers is not None:
                markerid = id(o)
                if markerid in markers:
                    raise ValueError("Circular reference detected")
                markers[markerid

总结

  • 提取特定键:可以根据需求选择并提取 JSON 数据中的某些字段。
  • 排序:JSON 数组可以按指定键进行排序,以便数据展示更符合逻辑。
  • 过滤:过滤掉不需要的字段,使数据更简洁。

这种动态提取和排序可以让你根据需求自定义 JSON 输出,增强灵活性。如果你有更复杂的需求,也可以在这些基础上进一步扩展功能。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2212969.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

华为FreeBuds 6i开降噪后底噪声大该如何解决?

华为FreeBuds 6i开了降噪会有沙沙的底噪声?最近看到一些小伙伴说这款耳机降噪效果比较好,但有时候在安静的环境下可以听到沙沙的底噪声,这是怎么回事? 我们先来聊一下降噪的原理:耳机内部的降噪系统通过麦克风采集外界…

智慧园区防护系统——提升园区安全性的关键工具

伴随着城市现代化推进,智慧园区已经成为当代城市基本建设不可或缺的一部分。智慧园区综合服务管理系统软件也被视为园区安全高效的关键工具之一。本文将从智慧园区安全性系统设计、作用、运用等多个方面详细的表述与分析。 一、设计 智慧园区防护系统设计方案应依据…

AI帮你读取总结数百个页面,AI搜索——未来的搜索引擎

AI搜索 引言实践测试kimi测试智谱测试 思考总结 引言 之前OpenAI O1刚上线时,就已称模型在使用COT思维链进行推理和自我反思后可以大大提升模型能力。最近Kimi和智谱都在内侧推出了AI搜索,使用下来感觉效果非常炸裂。AI通过COT思维链拆解你的问题 快速…

云原生后端技术:构建高可靠、可扩展的现代应用

✅作者简介:2022年博客新星 第八。热爱国学的Java后端开发者,修心和技术同步精进。 🍎个人主页:Java Fans的博客 🍊个人信条:不迁怒,不贰过。小知识,大智慧。 💞当前专栏…

iPhone变身健康卫士,假期作息紊乱不再怕

由于长假,许多人的作息时间表可能已经完全被打乱。晚上熬夜追剧、白天睡到自然醒,这样的生活虽然惬意,但对我们的身体健康却是个不小的挑战。幸运的是,iPhone手机内置的一系列健康功能,可以帮助我们重新找回规律的生活…

布隆过滤器原理及优缺点详解!

文章目录 引言工作原理示例展示优缺点优点缺点 使用场景总结 引言 布隆过滤器(Bloom Filter)是一种概率型数据结构,用于判断一个元素是否属于一个集合。它特别擅长处理大规模数据的快速查找,具有高效的空间利用率和查询速度。下面…

Flutter应用解析(一)

1、创建项目 1.1 新建 1.2 选择Flutter SDK的位置 1.3 项目名称 英文单词加下划线起名规范,其他默认即可。 1.4 点击运行 发生报错显示我们的JAVA版本不符合 1.5 更改版本设置 1.6 再次启动项目 2、分析页面代码 以下是lib/main.dart的源代码(为了阅…

论文中如何引用羲和的气象数据呢?

最近许多小伙伴在问“论文中使用了羲和能源气象大数据平台的数据,该怎么引用?”今天来给大家解答一下羲和的数据是否可靠以及在论文中的引用格式该如何表示。 羲和数源: 由南京图德科技有限公司自主研发,与美国国家航天局(NASA)、欧洲中期天…

Kubernetes最全详解,这真得收藏

号主:老杨丨11年资深网络工程师,更多网工提升干货,请关注公众号:网络工程师俱乐部 上午好,我的网工朋友 随着云计算的快速发展,容器技术成为了现代软件开发不可或缺的一部分。容器化技术,尤其是…

基于Asp.Net的校园报修信息系统的设计与实现---附源码54880

内容摘要 在当今数字化校园的背景下,为了提高校园报修管理的效率和便捷性,设计并实现了一个基于 Asp.Net 的校园报修信息系统。该系统旨在解决传统报修方式中存在的繁琐、低效和不及时等问题,为师生提供一个快速、准确、可靠的报修平台。 本系…

three.js 实现一个心形的着色器

three.js 实现一个心形的着色器 源链接:https://z2586300277.github.io/three-cesium-examples/#/codeMirror?navigationThreeJS&classifyshader&idheartShader 国内站点预览:http://threehub.cn github地址: https://github.com/z258630027…

天若OCR识别软件 使用教程 软件下载

F4(FnF4)快捷键打开软件,找到要识别的图片,直接选中要识别的区域,可直接识别出来。 如果识别失败,就在右键菜单里,重新识别

数据管理,数据治理,数据中心,数据中台,数据湖都是什么意思,有什么关系?

这些术语都与数据管理和处理相关,但它们各自关注的方面不同。下面我将逐一解释这些概念,并简要说明它们之间的关系。 数据管理 (Data Management) 数据管理是指规划、控制和提供数据及信息资产的过程。它包括了数据的获取、验证、存储、保护以及加工等一…

论文翻译 | LARGE LANGUAGE MODELS ARE HUMAN-LEVELPROMPT ENGINEERS

摘要 通过在自然语言指令上进行调节,大型语言模型(LLMs)已经展现出了作为通用计算机的惊人能力。然而,任务表现很大程度上取决于用于引导模型提示的质量,而最有效的提示通常是由人工精心设计的。受到经典程序合成和人类…

ppt在线生成工具有哪些?6个好用的做ppt软件盘点!

现代PPT作为工作和学习中的信息传递与展示工具,已被广泛使用。在商业或学术场景中,一个具备出色设计和内容的PPT幻灯片,能够最大限度吸引观众目光,同时提升信息传达效果。 然而同样不容忽视的是,传统的制作过程耗费时…

(接口测试)day01接口测试理论 http理论 接口测试流程 接口文档解析

一.接口测试理论 1.接口和接口测试 服务器为客户端开了一个验证接口(接口本质:函数方法)客户端向服务器传送的消息可以相当于函数的参数,接口是用来让客户端传递数据的 接口:相当于开了一个通道 当服务器要给客户端响…

什么!FPGA可以自行二次开发了?

问:什么~FPGA可以自行二次开发了? 答:目前市场上的标准采集卡通常不支持用户自行开发FPGA。但因为应用环境的需要,不仅仅只需要单一的数据采集流程,往往还需要在其中嵌入更复杂的运行和分析逻辑。为了解决这类问题,我…

【原创】java+springboot+mysql疫苗追踪管理系统设计与实现

个人主页:程序猿小小杨 个人简介:从事开发多年,Java、Php、Python、前端开发均有涉猎 博客内容:Java项目实战、项目演示、技术分享 文末有作者名片,希望和大家一起共同进步,你只管努力,剩下的交…

【STM32单片机_(HAL库)】6-6-1【串口通信UART、USART】【蓝牙遥控插座项目】HC-08蓝牙模块实验

通信示意图 1.硬件 STM32单片机最小系统HC-08蓝牙模块 2.软件 bluetooth驱动文件添加main.c程序 #include "sys.h" #include "delay.h" #include "led.h" #include "uart1.h" #include "bluetooth.h"int main(void) {…

日本IT|事务与IT营业岗位分别是什么?

在日本IT行业中,“事务”与“IT营业”是两个不同的岗位,它们各自承担着不同的职责。以下是对这两个岗位的详细解释: 一、事务岗位 定义与工作内容: 事务岗位通常指的是处理公司日常事务的职位,这些事务可能涉及IT派遣…