Convert between different types of JSON

Just wondering if anyone knows an easy way to convert between different types of JSON? I've had a look at an online converter but it wanted to wrap each row in curly quotes whereas I'm after:-

{
    "111222333": "the ball and chain",
    "123456789": "ted",
    "213546879": "harry",
    "312645978": "billy",
    "987654321": "sarah"
}

this format instead of

[
 {
   "number": "111222333",
   "name": "the ball and chain"
 },
 {
   "number": "123456789, ",
   "name": ""
 },
 {
   "number": "213546879",
   "name": "harry"
 },
 {
   "number": "312645978",
   "name": "billy"
 },
 {
   "number": "987654321",
   "name": "sarah"
 }
]

thank you!

Hi @dclear

I'm not clear from your two example pieces of JSON which you want to convert into the other. Although your post suggests you are starting with something else entirely and you want to get to the first example, but some online tool has given you the second example.

Exactly what format are you starting with?

Also do you mean JSON (which means the data is a string) or do you mean javascript objects?

You are looking for a kind of "transpose" function ?

Try a function node:

a = msg.payload // array input

o = {}
for(x=0;x<a.length;x++){
    
    o[a[x].number] = a[x].name     
}

return {payload:o}

Output:

{
    "111222333": "the ball and chain",
    "213546879": "harry",
    "312645978": "billy",
    "987654321": "sarah",
    "123456789, ": ""
}
1 Like

I don't think the input is an array.
I think Object.entries() may be useful here.

His input is an array and he wants the ouput as he showed in the first part of his post (it's written in reverse), unless I completely lost it.

Oh, sorry, you are right, I thought he wanted to convert the first to the second, but it is the other way round.

@bakman2 @Colin this is why I asked him to clarify because I think it is ambiguous as to what formats he has.

It's a follow on / related to this thread How to receive a phone number by MQTT then perform an Excel style vlookup to obtain a caller name?

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.