how to read .txt file having the following format.

1 回表示 (過去 30 日間)
MakM
MakM 2022 年 12 月 1 日
回答済み: Seth Furman 2022 年 12 月 7 日
I have text file attached, how can I read it like a table in MATLAB?
[{"ID":1,"Column_A":"red","Column_B":"apple","Column_C":0},{"ID":2,"Column_A":"orange","Column_B":"orange","Column_C":1},{"ID":2,"Column_A":"green","Column_B":"grapes","Column_C":3},{"ID":3,"Column_A":"purple","Column_B":"onion","Column_C":4}]

回答 (3 件)

cr
cr 2022 年 12 月 1 日
readtable(), importdata(), etc.
You may just drag and drop the file into workspace to launch importwizard. Make the appropriate settings and then choose generate code to see the underlying specifics.
Regards.
  4 件のコメント
MakM
MakM 2022 年 12 月 1 日
importwizard is crashing my MATLAB.
cr
cr 2022 年 12 月 2 日
Which version of matlab and what os are you on?

サインインしてコメントする。


Star Strider
Star Strider 2022 年 12 月 1 日
Use the readcell function —
C1 = readcell('https://www.mathworks.com/matlabcentral/answers/uploaded_files/1214888/example.txt')
C1 = 1×16 cell array
{'[{"ID":1'} {'Column_A:"red"'} {'Column_B:"apple"'} {'Column_C:0}'} {'{"ID":2'} {'Column_A:"orange"'} {'Column_B:"orange"'} {'Column_C:1}'} {'{"ID":2'} {'Column_A:"green"'} {'Column_B:"grapes"'} {'Column_C:3}'} {'{"ID":3'} {'Column_A:"purple"'} {'Column_B:"onion"'} {'Column_C:4}]'}
That will at least get it into your workspace.
.

Seth Furman
Seth Furman 2022 年 12 月 7 日
fileContents = string(fileread("example.txt"))
fileContents = "[{"ID":1,"Column_A":"red","Column_B":"apple","Column_C":0},{"ID":2,"Column_A":"orange","Column_B":"orange","Column_C":1},{"ID":2,"Column_A":"green","Column_B":"grapes","Column_C":3},{"ID":3,"Column_A":"purple","Column_B":"onion","Column_C":4}]"
jsonStruct = jsondecode(fileContents)
jsonStruct = 4×1 struct array with fields:
ID Column_A Column_B Column_C
t = struct2table(jsonStruct)
t = 4×4 table
ID Column_A Column_B Column_C __ __________ __________ ________ 1 {'red' } {'apple' } 0 2 {'orange'} {'orange'} 1 2 {'green' } {'grapes'} 3 3 {'purple'} {'onion' } 4
t = convertvars(t,[2 3],"string")
t = 4×4 table
ID Column_A Column_B Column_C __ ________ ________ ________ 1 "red" "apple" 0 2 "orange" "orange" 1 2 "green" "grapes" 3 3 "purple" "onion" 4

カテゴリ

Help Center および File ExchangeSpreadsheets についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by