【cue语言系列】03.json marshal和unmarshal

需求

初始有一个json
需要cue文件来帮助拼接一段形成一个新的json

简单版

image.png

import (
  "encoding/json"
)

// 原json Marshal之后的字符串
a: "{
    
    \"test1\":\"1\",\"test2\":\"2\"}"

// step1: 先unmarshal
b: json.Unmarshal(a)

// step2:拼接新的内容
c: {
    
    
    b
    "testNew": "new"   // 新内容
}

// step3: 转成字符串
cMarshal: json.Marshal(c)


复杂版

image.png

import (
  "encoding/json"
)

// 原json Marshal之后的字符串
a: "{
    
    \"test1\":\"1\",\"test2\":\"2\"}"

// step1: 先unmarshal
b: json.Unmarshal(a)

testValue:  {
    
    
    "111": "111"
    "222": "222"
}

// step2:拼接新的内容
c: {
    
    
    b
    "testNew": testValue  // 新内容
}

// step3: 转成字符串
cMarshal: json.Marshal(c)

进阶版2:一级拼接

image.png

import (
  "encoding/json"
)

// 原json Marshal之后的字符串
a: "{
    
    \"test1\":\"1\",\"test2\":\"2\"}"

// step1: 先unmarshal
b: json.Unmarshal(a)

testValue:  {
    
    
    "111": "111"
    "222": "222"
    "333": b.test2
}

// step2:拼接新的内容
c: {
    
    
    b
    "testNew": testValue  // 新内容
}

// step3: 转成字符串
cMarshal: json.Marshal(c)

进阶版2的另一种写法

image.png

import (
  "encoding/json"
)

self: {
    
    
    // step1: 先unmarshal
    b: json.Unmarshal("\(global.a)")
    
    testValue:  {
    
    
        "111": "111"
        "222": "222"
        "333": b.test2
    }
    
    // step2:拼接新的内容
    c: {
    
    
        b
        "testNew": testValue  // 新内容
    }
}

global: {
    
    
    // 原json Marshal之后的字符串
    a: "{
    
    \"test1\":\"1\",\"test2\":\"2\"}"
    
    
    // step3: 转成字符串
    cMarshal: json.Marshal(self.c)
}

进阶版3:两级拼接

image.png

import (
  "encoding/json"
)

// 原json Marshal之后的字符串
a: "{
    
    \"test1\":\"1\",\"test2\":\"2\"}"
a2: "{
    
    \"test1bbbb\":\"1\",\"test2bbbb\":\"2\"}"

// step1: 先unmarshal
b: json.Unmarshal(a)
b2: json.Unmarshal(a2)

testValue:  {
    
    
    "111": "111"
    "222": "222"
    "333": b.test2
    b2
}

// step2:拼接新的内容
c: {
    
    
    b
    "testNew": testValue  // 新内容
}

// step3: 转成字符串
cMarshal: json.Marshal(c)

进阶版3的另一种写法

image.png

import (
  "encoding/json"
)

self: {
    
    
    // step1: 先unmarshal
    b: json.Unmarshal("\(global.a)")
    b2: json.Unmarshal("\(global.a2)")
    
    testValue:  {
    
    
        b2
        "111": "111"
        "222": "222"
        "333": b.test2
    }
    
    // step2:拼接新的内容
    c: {
    
    
        b
        "testNew": testValue  // 新内容
    }
}


global: {
    
    
    // 原json Marshal之后的字符串
    a: "{
    
    \"test1\":\"1\",\"test2\":\"2\"}"
    a2: "{
    
    \"test1bbbb\":\"1\",\"test2bbbb\":\"2\"}"
    
    
    // step3: 转成字符串
    cMarshal: json.Marshal(self.c)
    
    
}

猜你喜欢

转载自blog.csdn.net/weixin_42072280/article/details/130565456