转换纯文本成JSON [英] converting plain text into json

查看:1203
本文介绍了转换纯文本成JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有,我想转换成JSON文件中的文本文件。 precisely,我想每行 $行$行转换:someid。有没有做到这一点使用bash脚本langage一个适当的方式或的JavaScript

例如

 我要
兑换
文成
JSON

将输出

  {{我要:1},{转换,2},{文成:3},{JSON :4}}


解决方案

您不能做这样的你预期的输出,因为你会产生一个语法错误,但你可以把多个对象在阵列来代替。事情是这样的:

HTML

 < D​​IV ID =ID>
我想
兑换
文成
JSON
< / DIV>

JS

  VAR textArr = document.querySelector('#ID')innerHTML.split('\\ n')。功能produceJSON(textArr){
  VAR ARR = [];  //我们循环从1到1比长度因为较少
  //前两个元素是空的,由于这样的工作分割
  对于(VAR I = 1,L = text.length - 1; I<升;我++){
    变种物镜= {};
    OBJ [文[我] =我;
    arr.push(OBJ);
  }
  返回JSON.stringify(ARR);
}VAR JSON = produceJSON(textArr);

DEMO

Suppose I have a text file that I want to convert into json file. Precisely, I want to convert each line $line to "$line":"someid" . Is there a proper way to do that using bash script langage or javascript.

For example

I want to
convert
text into
json

would output

{{"I want to":"1"},{"convert","2"},{"text into":"3"},{"json":"4"}}

解决方案

You can't do your expected output like that because you will produce a syntax error, but you can put multiple objects in an array instead. Something like this:

HTML

<div id="id">
I want to
convert
text into
json
</div>

JS

var textArr = document.querySelector('#id').innerHTML.split('\n');

function produceJSON(textArr) {
  var arr = [];

  // we loop from 1 to 1 less than the length because
  // the first two elements are empty due to the way the split worked
  for (var i = 1, l = text.length - 1; i < l; i++) {
    var obj = {};
    obj[text[i]] = i;
    arr.push(obj);
  }
  return JSON.stringify(arr);
}

var json = produceJSON(textArr);

DEMO

这篇关于转换纯文本成JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆