/JSON详解

JSON的全称是”JavaScript Object Notation”,意思是JavaScript对象表示法,它是一种基于文本,独立于语言的轻量级数据交换格式。

1,JSON的两种结构

JSON有两种表示结构,对象和数组。
对象结构以”{”大括号开始,以”}”大括号结束。中间部分由0或多个以”,”分隔的”key(关键字)/value(值)”对构成,关键字和值之间以”:”分隔,语法结构如代码。

{
    key1:value1,
    key2:value2,
    ...
}

其中关键字是字符串,而值可以是字符串,数值,true,false,null,对象或数组

数组结构以”[”开始,”]”结束。中间由0或多个以”,”分隔的值列表组成,语法结构如代码。

[
    {
        key1:value1,
        key2:value2 
    },
    {
         key3:value3,
         key4:value4   
    }
]

JSON in Python

The json library can

parse JSON file into a dict or list

json.load() : json file to dict

The library parses JSON into a Python dictionary or list.

json.loads() : json string to dictionary

It can also convert Python dictionaries or lists into JSON strings.

json.dumps() dict to json string

JSON can store Lists, bools, numbers, tuples and dictionaries. But to be saved into a file, all these structures must be reduced to strings. It is the string version that can be read or written to a file. Python has a JSON module that will help converting the datastructures to JSON strings.

dumps(): convert the python dictionary above into a JSON string that can be written into a file.

While the JSON module will convert strings to Python datatypes, normally the JSON functions are used to read and write directly from JSON files.

d = {
    'first_name': 'Guido',
    'second_name': 'Rossum',
    'titles': ['BDFL', 'Developer'],
}

print(json.dumps(d))
'{"first_name": "Guido", "last_name": "Rossum", "titles": ["BDFL", "Developer"]}'

dump(): dump a JSON string directly into a file.Remember only a JSON formatted string can be written to the file.

#Get the file name for the new file to write
filter = "JSON File (*.json)|*.json|All Files (*.*)|*.*||"
filename = rs.SaveFileName("Save JSON file as", filter)

# If the file name exists, write a JSON string into the file.
if filename:
    # Writing JSON data
    with open(filename, 'w') as f:
        json.dump(datastore, f)

The JSON module can also take a JSON string and convert it back to a dictionary structure:

Take the following string containing JSON data:

json_string = '{"first_name": "Guido", "last_name":"Rossum"}'
It can be parsed like this:

import json
parsed_json = json.loads(json_string)
and can now be used as a normal dictionary:

print(parsed_json['first_name'])
"Guido"

json.load()

json file : data.json
{
    "maps": [
        {
            "id": "blabla",
            "iscategorical": "0"
        },
        {
            "id": "blabla",
            "iscategorical": "0"
        }
    ],
    "masks": {
        "id": "valore"
    },
    "om_points": "value",
    "parameters": {
        "id": "valore"
    }
}


import json
from pprint import pprint
data = json.load(open('data.json'))
pprint(data)

With data, you can now also find values like so:
data["maps"][0]["id"]
data["masks"]["id"]
data["om_points"]

results matching ""

    No results matching ""