Преобразовать обычный текст в объект с парой ключ-значение - PullRequest
0 голосов
/ 10 ноября 2019

Я пытаюсь преобразовать обычный текст в JSON. У меня есть простой текст, как это. Мне удалось преобразовать фрукты, страну, цену и качество, так как они были в одной строке, но я не смог сделать это с помощью Description. Как поместить описание в один ключ: пара значений ???

Fruit: Apple
Country: Germany
Description: Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, 
 .
 Some other countries where this is found:
  * India
  * Austria
  * Jakarta
  * Sample
 .
 Lorem Ipsum is simply dummy text of the printing and typesetting industry, lorem Ipsum has been the industry's standard dummy text ever.
Price: 1500$
Quality: Excellent

Я хочу, чтобы результат был

{
Fruit: "Apple", 
Country: "Germany", 
Description: `Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, 
 .
 Some other countries where this is found:
  * India
  * Austria
  * Jakarta
  * Sample
 .
 Lorem Ipsum is simply dummy text of the printing and typesetting industry, lorem Ipsum has been the industry's standard dummy text ever.`,
 Price: "1500$",
 Quality: "Excellent"
}

Ответы [ 2 ]

0 голосов
/ 10 ноября 2019

Используйте, чтобы 2-я и другие строки многострочного строкового значения начинались с пробела:

Код (https://jsfiddle.net/koldev/toxz4y6a):

function join(key, value) {
    if (key === "") {
        return;
    }
    let line = "    \"" + key + "\": ";
    value = value.slice(0, -1);
    if (value.includes("\n")) {
        line += "`" + value + "`";
    } else {
        line += "\"" + value + "\"";
    }
    return line;
}

function parse(input) {
    let lines = input.split("\n");
    let key = "";
    let value = "";
    let output = "{\n";
    for (let i = 0; i < lines.length; i += 1) {
        let line = lines[i];
        if (line.startsWith(" ")) {
            value += line + "\n";
        } else {
            let keyValue = join(key, value);
            if (keyValue) {
                output += keyValue + ",\n";
            }
            let tokens = line.split(": ");
            key = tokens[0];
            value = tokens[1] + "\n";
        }
    }
    let keyValue = join(key, value);
    if (keyValue) {
        output += keyValue + "\n";
    }
    output += "}\n";
    return output;
}

let input = document.getElementById("input").innerText;
document.getElementById("output").innerText = parse(input);

Вывод:

{
    "Fruit": "Apple",
    "Country": "Germany",
    "Description": `Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, 
 .
 Some other countries where this is found:
  * India
  * Austria
  * Jakarta
  * Sample
 .
 Lorem Ipsum is simply dummy text of the printing and typesetting industry, lorem Ipsum has been the industry's standard dummy text ever.`,
    "Price": "1500$",
    "Quality": "Excellent"
}
0 голосов
/ 10 ноября 2019

Если продолжение строки действительно характеризуется начальным пробелом (отступом), как в случае с примером, то вы можете использовать регулярное выражение, например:

function toObject(text) {
    let obj = {};
    for (let [, key, val] of text.matchAll(/(\S.*?): ([^]*?)(?=$|\n\S)/g)) {
        obj[key] = val.replace(/\n /g, "\n"); // remove the indent
    }
    return obj;
}

// Example:
let text = `Fruit: Apple
Country: Germany
Description: Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, 
 .
 Some other countries where this is found:
  * India
  * Austria
  * Jakarta
  * Sample
 .
 Lorem Ipsum is simply dummy text of the printing and typesetting industry, lorem Ipsum has been the industry's standard dummy text ever.
Price: 1500$
Quality: Excellent`;

console.log(toObject(text));

Это создает объект JavaScript. Вы можете вызвать JSON.stringify для этого объекта, чтобы получить вывод JSON.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...