GVKun编程网logo

Python Json解析器(python json 解析)

9

在本文中,我们将带你了解PythonJson解析器在这篇文章中,我们将为您详细介绍PythonJson解析器的方方面面,并解答pythonjson解析常见的疑惑,同时我们还将给您一些技巧,以帮助您实现

在本文中,我们将带你了解Python Json解析器在这篇文章中,我们将为您详细介绍Python Json解析器的方方面面,并解答python json 解析常见的疑惑,同时我们还将给您一些技巧,以帮助您实现更有效的cJSON很好使用的一个json解析器、JSOND--一个更优的PHP JSON解析器、Python json类型有哪些?列举实例对Python json解析、Python json解析器允许重复键

本文目录一览:

Python Json解析器(python json 解析)

Python Json解析器(python json 解析)

我有一个具有以下结构的JSON文件:-

{
    "contributors": null,"truncated": false,"text": "@HomeShop18 #DreamJob to professional rafter","in_reply_to_status_id": null,"id": 421584490452893696,"favorite_count": 0,"source": "<a href=\"https://mobile.twitter.com\" rel=\"nofollow\">Mobile Web (M2)</a>","retweeted": false,"coordinates": null,"entities": {
        "symbols": [],"user_mentions": [
            {
                "id": 183093247,"indices": [
                    0,11
                ],"id_str": "183093247","screen_name": "HomeShop18","name": "HomeShop18"
            }
        ],"hashtags": [
            {
                "indices": [
                    12,21
                ],"text": "DreamJob"
            }
        ],"urls": []
    },"in_reply_to_screen_name": "HomeShop18","id_str": "421584490452893696","retweet_count": 0,"in_reply_to_user_id": 183093247,"favorited": false,"user": {
        "follow_request_sent": null,"profile_use_background_image": true,"default_profile_image": false,"id": 2254546045,"verified": false,"profile_image_url_https": "https://pbs.twimg.com/profile_images/413952088880594944/rcdr59OY_normal.jpeg","profile_sidebar_fill_color": "171106","profile_text_color": "8A7302","followers_count": 87,"profile_sidebar_border_color": "BCB302","id_str": "2254546045","profile_background_color": "0F0A02","listed_count": 1,"profile_background_image_url_https": "https://abs.twimg.com/images/themes/theme1/bg.png","utc_offset": null,"statuses_count": 9793,"description": "Rafter. Rafting is what I do. Me aur mera Tablet.  Technocrat of Future","friends_count": 231,"location": "","profile_link_color": "473623","profile_image_url": "http://pbs.twimg.com/profile_images/413952088880594944/rcdr59OY_normal.jpeg","following": null,"geo_enabled": false,"profile_banner_url": "https://pbs.twimg.com/profile_banners/2254546045/1388065343","profile_background_image_url": "http://abs.twimg.com/images/themes/theme1/bg.png","name": "Jayy","lang": "en","profile_background_tile": false,"favourites_count": 41,"screen_name": "JzayyPsingh","notifications": null,"url": null,"created_at": "Fri Dec 20 05:46:00 +0000 2013","contributors_enabled": false,"time_zone": null,"protected": false,"default_profile": false,"is_translator": false
    },"geo": null,"in_reply_to_user_id_str": "183093247","created_at": "Fri Jan 10 10:09:09 +0000 2014","filter_level": "medium","in_reply_to_status_id_str": null,"place": null
}

该文件中包含近1500个此类词典。我想知道在python中是否存在用于此类文件的延迟解析器。我希望解析器一次只返回一个字典,或者最坏的情况是逐行返回数据。我该怎么办?

cJSON很好使用的一个json解析器

cJSON很好使用的一个json解析器

cJSON: 一个用c写的一个简单好用的JSON解析器

下载地址: http://sourceforge.net/projects/cjson/files/?source=navbar

实例1: 创建一个简单的学生信息数组

cJSON* pRoot = cJSON_CreateObject();
cJSON* pArray = cJSON_CreateArray();
cJSON_AddItemToObject(pRoot,"students_info",pArray);
char* szOut = cJSON_Print(pRoot);

cJSON* pItem = cJSON_CreateObject();
cJSON_AddStringToObject(pItem,"name","chenzhongjing");
cJSON_AddStringToObject(pItem,"sex","male");
cJSON_AddNumberToObject(pItem,"age",28);
cJSON_AddItemToArray(pArray,pItem);

pItem = cJSON_CreateObject();
cJSON_AddStringToObject(pItem,"fengxuan");
cJSON_AddStringToObject(pItem,24);
cJSON_AddItemToArray(pArray,"tuhui");
cJSON_AddStringToObject(pItem,22);
cJSON_AddItemToArray(pArray,pItem);

char* szJSON = cJSON_Print(pRoot);
cJSON_Delete(pRoot);
//free(szJSON);

pRoot = cJSON_Parse(szJSON);
pArray = cJSON_GetobjectItem(pRoot,"students_info");
if (NULL == pArray)
{
return -1;
}

int iCount = cJSON_GetArraySize(pArray);
for (int i = 0; i < iCount; ++i)
{
cJSON* pItem = cJSON_GetArrayItem(pArray,i);
if (NULL == pItem)
{
continue;
}

string strName = cJSON_GetobjectItem(pItem,"name")->valuestring;
string strSex = cJSON_GetobjectItem(pItem,"sex")->valuestring;
int iAge = cJSON_GetobjectItem(pItem,"age")->valueint;
}

cJSON_Delete(pRoot); free(szJSON);

JSOND--一个更优的PHP JSON解析器

JSOND--一个更优的PHP JSON解析器

jsond:一个更优的php json解析器

首先,我们先来看看性能测试数据:

01 STR: { "i" : 23,  "array" : [1, null, false, true, [ "aha" ,  "baba" , 23, { "test" : 23}]]}
02 JSON:  time for 100000 iterations: 0.238321
03 JSOND: time for 100000 iterations: 0.236436

04

05 STR: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
06 JSON:  time for 100000 iterations: 0.110764
07 JSOND: time for 100000 iterations: 0.134212

08

09 STR: { "a" : 23.2234232}
10 JSON:  time for 100000 iterations: 0.078458
11 JSOND: time for 100000 iterations: 0.055479

12

立即学习“PHP免费学习笔记(深入)”;

13 STR: { "long-str" :  "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat." , }
14 JSON:  time for 100000 iterations: 0.881429
15 JSOND: time for 100000 iterations: 0.118529

16

17 STR: ... json_encode($_SERVER)
18 JSON:  time for 100000 iterations: 4.341252
19 JSOND: time for 100000 iterations: 1.960814

可以看到在大数据量的时候jsond的速度比json快多了。

根据自身情况,选择相应的安装方法,安装成功后,查看phpinfo:

使用方法:

mixed jsond_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] );string jsond_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] );string jsond_last_error_msg ( void );int jsond_last_error ( void );
登录后复制

Python json类型有哪些?列举实例对Python json解析

Python json类型有哪些?列举实例对Python json解析

任何语言之中都有json,本章节我们将为大家用实例去分析介绍如何使用 python 语言来编码,和用python语言去解码 json 对象。

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写。

JSON 函数

使用 JSON 函数需要导入 json 库:import json。

json函数表格.png

json.dumps

json.dumps 用于将 Python 对象编码成 JSON 字符串。

语法

json.dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, 
allow_nan=True, cls=None, indent=None, separators=None, encoding="utf-8", 
default=None, sort_keys=False, **kw)
登录后复制
实例

以下实例将数组编码为 JSON 格式数据:

#!/usr/bin/python
import json

data = [ { &#39;a&#39; : 1, &#39;b&#39; : 2, &#39;c&#39; : 3, &#39;d&#39; : 4, &#39;e&#39; : 5 } ]

json = json.dumps(data)
print json
登录后复制

以上代码执行结果为:

立即学习“Python免费学习笔记(深入)”;

[{"a": 1, "c": 3, "b": 2, "e": 5, "d": 4}]
登录后复制

使用参数让 JSON 数据格式化输出:

>>> import json
>>> print json.dumps({&#39;a&#39;: &#39;Runoob&#39;, &#39;b&#39;: 7}, sort_keys=True, indent=4, separators=(&#39;,&#39;, &#39;: &#39;))
{
    "a": "Runoob",
    "b": 7
 }
登录后复制

python 原始类型向 json 类型的转化对照表:

json-2.png

以上就是Python json类型有哪些?列举实例对Python json解析的详细内容,更多请关注php中文网其它相关文章!

Python json解析器允许重复键

Python json解析器允许重复键

我需要解析一个json文件,不幸的是,该文件不遵循原型。我的数据有两个问题,但是我已经找到了解决方法,所以我只在最后提一下,也许有人也可以提供帮助。

所以我需要解析这样的条目:

    "Test":{        "entry":{            "Type":"Something"                },        "entry":{            "Type":"Something_Else"                }           }, ...

json默认解析器更新字典,因此仅使用最后一个条目。我不得不以某种方式存储另一个,我也不知道如何做到这一点。我还必须将密钥以它们在文件中出现的顺序存储在几个字典中,这就是为什么我使用OrderedDict这样做的原因。它工作正常,所以如果有任何办法可以用重复的条目来扩展它,我将不胜感激。

我的第二个问题是,这个非常相同的json文件包含如下条目:

         "Test":{                   {                       "Type":"Something"                   }                }

当Json.load()函数到达json文件中的该行时,将引发异常。解决此问题的唯一方法是自己手动卸下内支架。

提前致谢

答案1

小编典典

您可以用JSONDecoder.object_pairs_hook来自定义JSONDecoder解码对象的方式。该挂钩函数将传递一个(key,value)通常会对其进行一些处理的成对列表,然后变成dict

但是,由于Python字典不允许重复的键(而且您根本无法更改键),因此在(key,value)解码JSON时,可以在挂钩中保持不变地返回对,并获得对的嵌套列表:

from json import JSONDecoderdef parse_object_pairs(pairs):    return pairsdata = """{"foo": {"baz": 42}, "foo": 7}"""decoder = JSONDecoder(object_pairs_hook=parse_object_pairs)obj = decoder.decode(data)print obj

输出:

[(u''foo'', [(u''baz'', 42)]), (u''foo'', 7)]

您如何使用此数据结构取决于您。如上所述,Python字典不允许重复的键,而且没有办法解决。您甚至将如何基于密钥进行查找?dct[key]会模棱两可。

因此,您既可以实现自己的逻辑来按期望的方式处理查找,也可以实现某种避免碰撞的功能,以使键(如果不是)变得唯一, 然后 从嵌套列表中创建字典。


编辑 :既然您说过要修改重复键以使其唯一,请按照以下步骤操作:

from collections import OrderedDictfrom json import JSONDecoderdef make_unique(key, dct):    counter = 0    unique_key = key    while unique_key in dct:        counter += 1        unique_key = ''{}_{}''.format(key, counter)    return unique_keydef parse_object_pairs(pairs):    dct = OrderedDict()    for key, value in pairs:        if key in dct:            key = make_unique(key, dct)        dct[key] = value    return dctdata = """{"foo": {"baz": 42, "baz": 77}, "foo": 7, "foo": 23}"""decoder = JSONDecoder(object_pairs_hook=parse_object_pairs)obj = decoder.decode(data)print obj

输出:

OrderedDict([(u''foo'', OrderedDict([(u''baz'', 42), (''baz_1'', 77)])), (''foo_1'', 7), (''foo_2'', 23)])

make_unique函数负责返回无冲突键。在这个例子中,它只是后缀与关键_n地方n是一个递增计数器-只是它适应您的需求。

由于object_pairs_hook完全按照JSON文档中出现的顺序接收对,因此也可以使用来保留该顺序OrderedDict,我也将其包括在内。

我们今天的关于Python Json解析器python json 解析的分享已经告一段落,感谢您的关注,如果您想了解更多关于cJSON很好使用的一个json解析器、JSOND--一个更优的PHP JSON解析器、Python json类型有哪些?列举实例对Python json解析、Python json解析器允许重复键的相关信息,请在本站查询。

本文标签: