从一串嵌套键构建嵌套JSON [英] Build nested JSON from string of nested keys

查看:102
本文介绍了从一串嵌套键构建嵌套JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些正在使用nodeJS读取的csv文件.在阅读之前,我将每个文件都转换为文本.

I have csv files that I am reading using nodeJS. I convert each file to text before reading.

文件中的每一行都有以'='分隔的数据.

Each line in the file have data delimited with '='.

每行看起来像

data.location.degree.text=sometexthere

"="之前的第一部分代表我的应用程序中json对象的索引.我的目的是解析这些数据并为其构建一个json表示,以便上面的行成为

The first portion before the "=" represent an index to a json object in my app. I aim to parse this data and build a json representation of it so that the line above becomes

data:{
  location:{
    degree:{
      text: 'sometexthere'
    }
  }
}

使用javascript/node js;如何将应该表示嵌套JSON键序列的字符串转换成上述的json对象?

Using javascript/ node js; How can I convert a string which is supposed to represent a sequence of nested JSON keys, into a json object like above?

推荐答案

您可以拆分路径并检查以下元素是否存在.如果没有,则将对象分配给新属性.

You could split the path and make a check if the following element exist. If not assign an object to the new property.

然后返回属性值.

最后指定值.

function setValue(object, path, value) {
    path = path.replace(/[\[]/gm, '.').replace(/[\]]/gm, ''); //to accept [index]
    var keys = path.split('.'),
        last = keys.pop();

    keys.reduce(function (o, k) { return o[k] = o[k] || {}; }, object)[last] = value;
}

var data = {};

setValue(data, 'location.degree.text', 'sometexthere');
console.log(data);

这篇关于从一串嵌套键构建嵌套JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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