0
I’m doing a task in Python that requires me to search some data in a database. One of these values returns in the format of a JSON, the problem is that I need to make a "split" of these data since, this JSON is returning with all values in the same field.
Below is an example of JSON returned:
{"phones": "(11) 91234-5678",
"emails": "[email protected]",
"branches":
[{"address":"Rua de exemplo",
"city":"São Paulo",
"city_area": XXXX,
"region":XXXX,
"country":"Brasil"}],
"web":"www.siteexemplo.com.br"
}
Basically, I need to separate this into different fields, which would look something like this:
{
"phones": "(11) 91234-5678"
},
{
"emails": "[email protected]"
},
{
"address": "Rua de exemplo"
},
{
"city": "São Paulo"
},
{
"city_area": XXXX
},
{
"region":XXXX
},
{
"country":"Brasil"
},
{
"web": "www.siteexemplo.com.br"
}
Edit: At the moment I receive these values from a single column of a database table (Mysql). Need to separate all these values so that each one becomes a column in a new table.
Will you render this information with front in oq? (javascript for example)
– Rafael Rotiroti
Then you would not be separating into different "fields", but rather representing an object for each property. And what it would look like in case there’s more than one city inside
branches: [{},..]
??– Leandro Angelo
The JSON you want to create (multiple "loose" objects, one after the other) is not valid. To be valid, these objects would have to be in a list, see: https://ideone.com/n4s3Bw. But actually I would go back one step and see why it needs to be so. One of the advantages of JSON is precisely to group together in a single object all the data that makes sense to be together. I see no advantage in separating in this way, unless there is some justification that has not been mentioned. If you can [Edit] the question putting a little more context, suddenly even suggest a better solution...
– hkotsubo
@Rafaelrotiroti, I will insert this data into a table. They need to be in different columns. Today I have the "contact" column that returns all this data in the same column. I want to separate this data each in its column.
– P. Junior
@Leandroangelo I need to separate these data, each in its column in the database. This case that you mentioned does not come to occur.
– P. Junior
@hkotsubo Thanks for the suggestion. I will edit question.
– P. Junior
Why do you need to separate so to insert into the bank? You could not just use
objeto_json['phones']
,objeto_json['emails']
, etc, when to insert? Or does the function you are using in any way require the format to be this? When usingjson.loads
, as the answer suggests below, vc gets the JSON object with all available fields, I don’t see why generate another JSON with each field in a separate object...– hkotsubo