Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript将字符串拆分为具有属性的对象_Javascript_Json - Fatal编程技术网

JavaScript将字符串拆分为具有属性的对象

JavaScript将字符串拆分为具有属性的对象,javascript,json,Javascript,Json,我遇到了一个问题,API给了我一个长字符串,其中包含多个需要分解成对象的项。以下是字符串的示例: "Child 1 First Name: Ali\nChild 1 Gender: Female\nChild 1 Hair Color: Blonde\nChild 1 Hair Style: Wavy\nChild 1 Skin Tone: Tan\nChild 2 First Name: Morgan \nChild 2 Gender: Female\nChild 2 Hair Color:

我遇到了一个问题,API给了我一个长字符串,其中包含多个需要分解成对象的项。以下是字符串的示例:

"Child 1 First Name: Ali\nChild 1 Gender: Female\nChild 1 Hair Color: Blonde\nChild 1 Hair Style: Wavy\nChild 1 Skin Tone: Tan\nChild 2 First Name: Morgan \nChild 2 Gender: Female\nChild 2 Hair Color: Brown\nChild 2 Hair Style: Ponytail\nChild 2 Skin Tone: Light\nRelationship 1 to 2: Brother\nRelationship 2 to 1: Brother\n"
它使用
\n
将所有内容拆分为多行。字符串是API发送的较大对象的一个属性。出于某种原因,当我尝试对其使用
.split
方法时,比如(下面的完整代码),我需要使用
JSON.stringify
,以便让我的函数开始工作

这是我的全部代码:

让rawNoteData=order.customer.note;
让data=JSON.stringify(rawNoteData);
设foo=data.split(“\n”).reduce(函数(obj、str、index){
设strParts=str.split(“:”);
obj[strParts[0]。替换(/\s+/g',)]=strParts[1];
返回obj;
}, {});

console.log(foo)如果
order.customer.note
是您的示例字符串,那么这应该可以:

let data=“儿童1名:阿里\n儿童1性别:女性\n儿童1发色:金发\n儿童1发色:波浪状\n儿童1肤色:棕褐色\n儿童2名:摩根\n儿童2性别:女性\n儿童2发色:棕色\n儿童2发色:马尾辫\n儿童2肤色:浅\n关系1至2:兄弟\n关系2至1:兄弟\n”;

//让data=JSON.stringify(rawNoteData) 我可以想出两种方法将字符串转换为对象:

  • 创建一个JSON字符串,并使用
    JSON\parse
    进行解析
  • const str=“儿童1名:阿里\n儿童1性别:女性\n儿童1发色:金发\n儿童1发色:波浪状\n儿童1肤色:棕褐色\n儿童2名:摩根\n儿童2性别:女性\n儿童2发色:棕色\n儿童2发色:马尾辫\n儿童2肤色:浅\n关系1至2:兄弟\n关系2至1:兄弟\n”;
    常量对象=(str)=>{
    const json=str.replace(/([^\:]+)\:([^\n]+)\n/g,(\ux,p1,p2)=>{
    返回“${p1.replace(/\s+/g,”)}”:“${p2.trim()}”,`;
    });
    返回JSON.parse(`{${JSON.slice(0,-1)}}}`);
    };
    console.log(toObject(str))
    
    let data = 'Child 1 First Name: Ali\nChild 1 Gender: Female\nChild 1 Hair Color: Blonde\nChild 1 Hair Style: Wavy\nChild 1 Skin Tone: Tan\nChild 2 First Name: Morgan \nChild 2 Gender: Female\nChild 2 Hair Color: Brown\nChild 2 Hair Style: Ponytail\nChild 2 Skin Tone: Light\nRelationship 1 to 2: Brother\nRelationship 2 to 1: Brother\n';
    let target = {};
    
    data.split('\n').forEach((pair) => {
      if(pair !== '') {
        let splitpair = pair.split(': ');
        let key = splitpair[0].charAt(0).toLowerCase() + splitpair[0].slice(1).split(' ').join('');
        target[key] = splitpair[1];
      }
    });
    
    console.dir(target);
    

    生成一个类似于您所要求的对象

    您一定在双重字符串化方面遇到了一些问题。如果我根据提供的数据中的初始字符串运行reduce,只需稍作修改,它看起来与您期望的完全一样:。通过打开控制台查看小提琴。这几乎正是OP正在做的事情,它工作得很好,是的。但这是一个怎样的答案?代码修改和解释?问题中显然还有另一个问题。如果按照原始
    数据
    字符串中的方式应用OP的代码,则不会得到与OP所说的相同的结果。我认为答案在于找出初始字符串的错误所在。@FreemanLambda当然可以。使
    rawNoteData
    等于示例字符串,您将得到OP所称的“疯狂外观对象”。@J.Titus yes!!这似乎奏效了!lol在想了2秒钟后就这么做了。