Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to populate a MySQL 5.7 table with data from a json file with line breaks on Win7?

I have following example json file and I'm trying to populate a MySQL table with it. Since MySQL 5.7 supports json as a native datatype I thought this shouldn't be a problem, but MySQL's json validator seems to have a problem with the line breaks inside the file. As soon as I get rid of all line breaks and write my example file in one line, it works perfectly.

[
{
    "somestuff": [
        {
            "field1": "val1",
            "field2": 17,
            "field3": 27,
            "field4": 42,
            "field5": 73
        },
        {
            "field1": "val2",
            "field2": 3,
            "field3": 12,
            "field4": 13,
            "field5": 100
        }
    ],
    "field0": "image",
    "path": "some path"
}
]

I know json natively has problems with strings containing backslashes, but even when writing any kind of word instead of the path, the MySQL json validator still can't completely read the json file and just stops before the first line break. I still get following error:

Error Code: 3140. Invalid JSON text: "Invalid value." at position 1 in value (or column) '['. 

when using following query:

-- create test table for json data
CREATE TABLE IF NOT EXISTS jsons_test(
       annotation_id INT AUTO_INCREMENT NOT NULL UNIQUE, 
        json_data json);
LOAD DATA LOCAL INFILE 'C:\\some\\path\\test.json'
INTO table json_test(json_data);

I guess this most probably happens because of the line break encoding, but I still don't know if there's any workaround to solve it.

UPDATE: I found a solution on my own... By adding LINES TERMINATED BY '\\n' I could successfully populate the table with the json data and make use of the advantages of MySQL's new json support.

like image 470
user3168930 Avatar asked Oct 19 '22 11:10

user3168930


1 Answers

I found a solution for my problem: see UPDATE

like image 141
user3168930 Avatar answered Oct 21 '22 05:10

user3168930