JSON檔案的讀取操作詳解

2021-09-13 22:13:13 字數 1810 閱讀 8106

python操作json檔案

下面有一段json形式的字串,它是str型別,通過python轉化成可操作的資料結構

import json

str=

'''[,]

'''print

(type

(str)

)data = json.

loads

(str)

print

(data)

print

(type

(data)

)

這裡使用loads()方法,將字串轉化為json物件

那麼,如何獲取對應的內容呢

data[0].get('name')

data[0]['name']

#索引0表示得到第乙個字典元素,name表示第乙個字典的key,也即是json的屬性,

我們一般使用第一種方法,第一種方法獲取不到會返回none.

##這裡說個重點,json資料需要用雙引號來包圍,不能使用單引號,不然易出現解析錯誤

import json

with open('data.json','r') as file:

str = file.read()

data = json.loads(str)

print(data)

把檔案的內容結構化輸出

improt json

data =

with

open

('data.json'

,'w'

)as file:

file.

write

(json.

dumps

(data)

)

dumps()方法將json物件轉為字串,然後呼叫檔案的寫方法,寫入,這種寫入沒有格式,可以就加入引數indent,儲存為json格式

improt json

data =

with

open

('data.json'

,'w'

)as file:

file.

write

(json.

dumps

(data,indent=2)

)

這樣得到的內容會有縮排,會更清晰。

improt json

data =

with

open

('data.json'

,'w'

)as file:

file.

write

(json.

dumps

(data,indent=2)

)

這裡得道德大哥,會是乙個unicode字串,並不是我想要的。那麼就需要指定引數ensure_ascii為false

improt json

data =

with

open

('data.json'

,'w'

,encoding=

'utf-8'

)as file:

file.

write

(json.

dumps

(data,indent=

2,ensure_ascii=false)

)

這樣就能輸出中文了。

Unity讀取Json和txt檔案操作

自己寫了一些載入json和讀取txt檔案的小方法,基本都是讀取很容易的,因為發現每次訪問什麼我都得自己重新再想在寫好麻煩啊,在這記下來以後省事哈哈哈 using system.io using system.text using unityengine public static class jso...

讀取本地的json檔案

最近寫專案需要讀取本地的json檔案,然後悲催的發現前端新手的我居然不會,查查找找發現這東西並不難,但是應該是比較常用的,畢竟json太好用了!我是直接用的jquery實現的,但是ajax也可以,不過我用的ajax的簡約版 getjson url,function 如下 function getsc...

讀取本地json檔案,解析json

data.json 檔案同目錄下 import json 引入模組 count 1 開啟乙個json檔案 data open data.json encoding utf 8 轉換為python物件 strjson json.load data flag false lockflag false w...